2015-04-28 41 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]