有没有办法从JSON文件中获取随机值?我的JSON包含很多基于相同音乐艺术家的内容,所以我想更随机地显示数据并在之后添加一个显示更多按钮...
所以我的JSON看起来像这样:
[
data: [{
"name" : "rihanna",
"song" : "pour it up"
},
{
"name" : "rihanna"
"song" : "diamonds"
},
{
"name" : "ladygaga"
"song" : "lovegame"
},
{
"name" : "ladygaga"
"song" : "lovegame"
},
{
"name" : "ladygaga"
"song" : "pokerface"
},
{
"name" : "ladygaga"
"song" : "alejandro"
},
{
"name" : "fergie"
"song" : "fergalicious"
},
{
"name" : "fergie"
"song" : "clumsy"
},
etc etc
那么,有没有办法实现这个目标?
答案 0 :(得分:1)
试试这个:)
var random = Math.floor(Math.random() * jsonObject.length);
var rData = jsonObject[random];
P.S。 :其中jsonObject是你的数据属性。
答案 1 :(得分:0)
以下是如何实现它的方法。的 PLUNKER 强>
$(document).ready(function() {
$('button').on('click', function() {
getRandom();
var html = template(context);
$('#artistlist').html(html);
});
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
var musicArray = [{
"name": "rihanna",
"song": "pour it up"
}, {
"name": "rihanna",
"song": "diamonds"
}, {
"name": "ladygaga",
"song": "lovegame"
}, {
"name": "ladygaga",
"song": "lovegame"
}, {
"name": "ladygaga",
"song": "pokerface"
}, {
"name": "ladygaga",
"song": "alejandro"
}, {
"name": "fergie",
"song": "fergalicious"
}, {
"name": "fergie",
"song": "clumsy"
}];
var context = {
music: []
};
var musicClone = $.extend(true, [], musicArray);
function getRandom() {
var i = 2;
while (i-- && musicClone.length >= 1) {
var random = Math.floor(Math.random() * musicClone.length);
var data = musicClone[random];
context.music.push(data);
musicClone.splice(random, 1);
}
}
});