【问题标题】:Get random variable with javascript使用javascript获取随机变量
【发布时间】: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


【解决方案1】:

使用countries 对象,然后使用Object.values 检索所有国家/地区的数组,然后获取该数组的随机国家/地区。

const countries = {
  sweden: {
    name: 'Sweden',
    capacity: 120,
    common: ['AX8', 'BLL', 'FAV38']
  },
  france: {
    name: 'France',
    capacity: 560,
    common: ['BA', 'BLL', 'EXON']
  }
}

function getRandom(arr) {
  return arr[Math.floor(Math.random() * arr.length)]
}

let randomCountry = getRandom(Object.values(countries));

console.log(`Random country: ${randomCountry.name}`);
console.log('Random country info', randomCountry);

countries 可以直接是一个数组,如果你永远不会通过它的名字直接访问一个国家:countries.sweden,这样你可以避免Object.values

const countries = [{/*..*/}];

let randomCountry = getRandom(countries);

【讨论】:

    【解决方案2】:

    使用以下内容:

    sweden.common[Math.floor(Math.random()*sweden.common.length)]
    france.common[Math.floor(Math.random()*france.common.length)]
    

    【讨论】:

    • 你误解了这个问题。这不是来自每个 common 数组的随机值,而是随机国家对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 2017-08-24
    相关资源
    最近更新 更多