最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Picking a random json object - Stack Overflow

programmeradmin5浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论