【发布时间】:2018-09-17 11:03:20
【问题描述】:
我有多个包含国家信息的局部变量。
let sweden = {
name: 'Sweden',
capacity: 120,
common: ['AX8', 'BLL', 'FAV38']
};
let france = {
name: 'France',
capacity: 560,
common: ['BA', 'BLL', 'EXON']
};
我需要随机选择一个国家并显示信息。怎么可能呢?
谢谢!
【问题讨论】:
-
将这些变量添加到数组中,生成0到array.length - 1之间的随机整数,选择array[randomInteger]
-
那些对象不应该是变量,它们应该是另一个对象的属性,即
let counties = {sweden: {…}, france: {…}}。随机选择一个看起来像let entries = Object.entries(countries); let [randomCountryName, randomCountryObject] = entries[Math.floor(Math.random() * entries.length)];。 -
countries = [ { name: 'Sweden', capacity: 120, common: ['AX8', 'BLL', 'FAV38'] }, { name: 'France', capacity: 560,常见的:['BA', 'BLL', 'EXON'] } ]; console.log(countries[Math.floor(Math.random() * countries.length)])
标签: javascript variables random scope