挑选一个随机的json对象

时间:2015-08-17 12:55:06

标签: javascript jquery arrays ajax

我有json数据。

[
["Mango","M"],
["Lychee","L"],
["Pineapple","P"],
["Banana","B"]
]

我需要能够随机选择一个数组项(例如["Pineapple","P"])。我该如何随机选择?

var alphabetNum = "";
$.ajax (
   { 
    url:"getalphabet.json"
   }).done(function(data) {
        alphabetNum = data;
});

1 个答案:

答案 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]);