javascript - Picking a random json object - Stack Overflow

I've got json data.[["Mango","M"],["Lychee","L"],["

I've got json data.

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

I need to be able to pick an Array item randomly (e.g. ["Pineapple","P"]). How can I do a random pick?

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

I've got json data.

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

I need to be able to pick an Array item randomly (e.g. ["Pineapple","P"]). How can I do a random pick?

var alphabetNum = "";
$.ajax (
   { 
    url:"getalphabet.json"
   }).done(function(data) {
        alphabetNum = data;
});
Share Improve this question edited Aug 17, 2015 at 13:03 Barrie Reader 10.7k11 gold badges77 silver badges141 bronze badges asked Aug 17, 2015 at 12:55 BekkiBekki 7292 gold badges12 silver badges20 bronze badges 5
  • 1 1) You have array 2) Array is integer indexed 3) produce random number [0, length) 4) alphabetNum[i] – Andrey Commented Aug 17, 2015 at 12:59
  • data is the array you want pick randomly from? – Taher Rahgooy Commented Aug 17, 2015 at 12:59
  • 1 That is not a JSON object. – IfTrue Commented Aug 17, 2015 at 13:00
  • @IfTrue it is actually a valid JSON (page 2 ecma-international/publications/files/ECMA-ST/ECMA-404.pdf) – Andrey Commented Aug 17, 2015 at 13:20
  • @Audrey I wasn't saying it was not valid JSON, I said it wasn't a JSON "object" which the original post said it was. I just wanted to make sure in case OP did not know there is a difference that they can then go out and learn the difference between an array and an object. You can see the history before it was edited by clicking "edited [time past] ago" in the OP. – IfTrue Commented Aug 17, 2015 at 14:26
Add a ment  | 

1 Answer 1

Reset to default 7

Just take Math.random() and the length of the array as factor.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744306357a4567731.html

相关推荐

  • javascript - Picking a random json object - Stack Overflow

    I've got json data.[["Mango","M"],["Lychee","L"],["

    7天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信