【发布时间】:2017-10-24 09:55:58
【问题描述】:
我想从一个数组对象中选择一个随机索引,这个对象包含两个键作者和图像数组。我可以从数组对象中选择一个随机索引,但是我如何也可以根据图像数组从图像数组中选择一个随机索引随机选择的数组对象索引?
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?
【问题讨论】:
-
在变量上保存 resourcesObject[Math.floor(Math.random() * resourcesObject.length)] 并使用该变量来查找随机索引
-
这样?
console.log(savedIndex.images1[Math.floor(Math.random() * 3)]);但如果它是包含 images2 的另一个对象,那将是一个错误或者我做错了?
标签: javascript arrays json object random