我想从一个数组对象中选择一个随机索引,这个对象包含两个键 author 和 images 数组。我可以从数组对象中选择一个随机索引,但是我如何根据随机选择数组对象索引?
let resourcesObject = [
{
"author" : "photographer1",
"images1": ['cat1','cat2','cat3']
},
{
"author" : "photographer2",
"images2": ['dog1', 'dog2', 'dog3', 'dog4']
}
];
console.log(resourcesObject[Math.floor(Math.random() * resourcesObject.length)]); // gives me a random object as expected { author: 'photographer2',images2: [ 'dog1', 'dog2', 'dog3', 'dog4' ] }, //but i also want to select a random index from the images2 how would i do that?
最佳答案
希望对您有所帮助! 它对我很有用:
var resourcesObject = [
{
"author" : "photographer1",
"images1": ['cat1','cat2','cat3']
},
{
"author" : "photographer2",
"images2": ['dog1', 'dog2', 'dog3', 'dog4']
}
];
function randomize(n){
return Math.floor(Math.random() * n);
}
var n = resourcesObject.length;
var randomIndex = randomize(n);
var selectedObj = resourcesObject[randomIndex]['images' + (randomIndex + 1)];
var randomImg = selectedObj[(Math.floor(Math.random() * selectedObj.length))];
console.log(randomImg);
关于javascript - 如何从随机选择的对象中选择随机索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46907458/