admin管理员组文章数量:1405617
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
1 Answer
Reset to default 7Just 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]);
本文标签: javascriptPicking a random json objectStack Overflow
版权声明:本文标题:javascript - Picking a random json object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744306356a2599812.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论