2016-08-07 36 views
1

使用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等,但它顯然沒有發生。幫幫我?

回答

0

把你的項目在數組中:使用您的getRandomInt

items = [item1, item2]; 

下一步,選擇(打印)隨機項目的名稱()函數:

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

你應該把你的項目在一個陣列,而不是使用多個變量:

var items = [ 
    { 
     name: 'apple', 
     // ... 
    }, 
    { 
     name: 'cherry', 
     // ... 
    } 
]; 

// Pick a random item (slightly biased) 
var item = items[Math.random() ℅ items.length]; 
0
  • 將對象存儲在一個數組中
  • 改進隨機生成器。

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);

0

把你的項目在數組中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);