2015-04-28 37 views
-1

我有這樣的一些代碼,增加了圖像的「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)圖像之一,然後檢索其屬性,以便我可以使用它們來創建圖像?

+1

[的Math.random()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random )+數組的大小(在jsonparsing之後)+使用結果作爲索引=您的答案 – KarelG

+1

您沒有數組。你有JSON對象。 –

+0

試試這個var item = imagesArray [Math.floor(Math.random()* imagesArray .length)]; – Sushil

回答

3

var imagesArray = [ 
 
    { 
 
    id: 'xboxLogo', 
 
    src: "images/xboxLogo.png" 
 
    }, 
 
    { 
 
    id: 'playStatLogo', 
 
    src: "images/playStatLogo.png" 
 
    }, 
 
    { 
 
    id: 'wiiLogo', 
 
    src: "images/wiiLogo.png" 
 
    } 
 
]; 
 

 
$('button').click(function() { 
 
    var randomImage = imagesArray[Math.floor(Math.random() * imagesArray.length)]; 
 
    $('p').text(randomImage.src); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<p></p> 
 

 
<button>pick random</button>

+0

很棒,很好,很簡單,並有一個可運行的代碼片段:)謝謝,當我可以的時候會接受你的回答:)) –

1

生成一個隨機數,它將成爲所需圖像的索引。

var keys = Object.keys(imagesArray); 
var n = keys.length; 
var index = Math.floor(Math.random() * n); 
var randomKey = keys[index] 
var image = imagesArray[randomKey]