从生成的数字中选择变量

Choosing a variable from a generated number

本文关键字:选择 变量 数字      更新时间:2023-09-26

使用javascript,我有一些变量。

var item1 = {
    name : 'apple',
    color : 'red',
    type : 'fruit'
    //etc
};
var item2 = {
    name : 'rose',
    color : 'red',
    type : 'plant'
    //etc
};

我想根据数字选择所述项目。我想这样做。

var select;
function getRandomInt(min, max) {
   return Math.floor(Math.random() * (max - min + 1)) + min;
}
select = Math.floor(Math.random() * 2) + 1;

然而,我在调用这些项目时遇到了问题。我原以为这只是item[select].name等。但显然没有发生。帮助

将您的物品放入数组:

items = [item1, item2];

接下来,使用getRandomInt((函数选择(打印(一个随机项目的名称:

console.log(items[getRandomInt(0,items.length - 1)].name);

您应该将项目放在一个数组中,而不是使用多个变量:

var items = [
    {
        name: 'apple',
        // ...
    },
    {
        name: 'cherry',
        // ...
    }
];
// Pick a random item (slightly biased)
var item = items[Math.random() ℅ items.length];
  • 将对象存储在阵列中
  • 改进随机生成器

var item = [{
  name: 'apple',
  color: 'red',
  type: 'fruit'
}, {
  name: 'rose',
  color: 'red',
  type: 'plant'
},{
  name: 'apple1',
  color: 'red1',
  type: 'fruit1'
}, {
  name: 'rose1',
  color: 'red1',
  type: 'plant1'
}];
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
console.log(item[getRandomInt(0, item.length)].name);

将项目放入数组items,然后使用items[select].name

var item1 = {
    name : 'apple',
    color : 'red',
    type : 'fruit'
    //etc
};
var item2 = {
    name : 'rose',
    color : 'red',
    type : 'plant'
    //etc
};
var item = [item1, item2];
var select = "";
    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    select = Math.floor(Math.random() * 2) ;
console.log(item[select].name);