我有這樣的一些代碼,增加了圖像的「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