我有这样的一些代码,增加了图像的“imageContainer”如何从对象数组中检索随机对象?使用Javascript
$('.imageContainer').prepend('<img id="xboxLogo" src="images/xboxLogo.png"/>')
我有这样的对象数组:
var imagesArray = {
xboxLogo : {
id : 'xboxLogo';
src: "images/xboxLogo.png";
},
playStatLogo : {
id : 'playStatLogo';
src: "images/playStatLogo.png";
},
wiiLogo : {
id : 'wiiLogo';
src: "images/wiiLogo.png";
}
}
我想要做的就是有一个功能,我调用将图像添加到'imageContainer',但我想要从'imagesArray'中随机选取图像。我如何随机获得3(xbox,playStation,wii)图像之一,然后检索其属性,以便我可以使用它们来创建图像?
[的Math.random()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random )+数组的大小(在jsonparsing之后)+使用结果作为索引=您的答案 – KarelG
您没有数组。你有JSON对象。 –
试试这个var item = imagesArray [Math.floor(Math.random()* imagesArray .length)]; – Sushil