我有json数据。
[
["Mango","M"],
["Lychee","L"],
["Pineapple","P"],
["Banana","B"]
]
我需要能够随机选择一个数组项(例如["Pineapple","P"]
)。我该如何随机选择?
var alphabetNum = "";
$.ajax (
{
url:"getalphabet.json"
}).done(function(data) {
alphabetNum = data;
});
答案 0 :(得分:5)
只需将Math.random()
和数组的长度作为因子。
var array = [
["Mango","M"],
["Lychee","L"],
["Pineapple","P"],
["Banana","B"]
];
var randomItem = array[Math.random() * array.length | 0];
// take only the element with index 0
alert(randomItem[0]);