我想从数组对象中选择一个随机索引,这个对象包含两个键作者和图像数组..我可以从数组对象中选择一个随机索引但是我如何从图像数组中选择一个随机索引基于随机选择数组对象索引?
<ComboBox Name="cbForms" SelectionChanged="cbForms_SelectionChanged" HorizontalAlignment="Left" Margin="10,289,0,0"
VerticalAlignment="Top" Width="139"
SelectedIndex="0">
<ComboBoxItem>Polygon</ComboBoxItem>
<ComboBoxItem>Rechteck</ComboBoxItem>
<ComboBoxItem>Dreieck</ComboBoxItem>
<ComboBoxItem>Kreis</ComboBoxItem>
</ComboBox>
答案 0 :(得分:1)
希望它有所帮助! 它对我有用:
[
{
"user": "string",
"semester": "string",
"subject_name": "string",
"subject_relevance": 1,
"subject_details": 0,
"id": "string"
}
]
答案 1 :(得分:0)
这给出了随机对象
<!DOCTYPE html>
<html>
<body>
<p>Looping through arrays inside arrays.</p>
<p id="demo"></p>
<script>
var myObj;
myObj = [
{
"author" : "photographer1",
"images1": ['cat1','cat2','cat3']
},
{
"author" : "photographer2",
"images2": ['dog1', 'dog2', 'dog3', 'dog4']
}
]
document.getElementById("demo").innerHTML = myObj[Math.floor(Math.random() * 2) + 0 ];
</script>
</body>
</html>
答案 2 :(得分:0)
这是一个很好的例子,可以将功能提取到一个小函数中,根据数组的长度选择索引
function getRandomIndex( array ) {
return parseInt( Math.random() * array.length );
}
然后您可以将其用作:
let resourcesObject = [
{
"author" : "photographer1",
"images1": ['cat1','cat2','cat3']
},
{
"author" : "photographer2",
"images2": ['dog1', 'dog2', 'dog3', 'dog4']
}
];
let resourceIndex = getRandomIndex( resourcesObject );
// is images part of the index, or is there a reason to have images1 or images2
let imageProp = 'images' + (resourceIndex + 1);
let imageIndex = getRandomIndex( resourcesObject[resourceIndex][imageProp] );
let image = resourcesObject[resourceIndex][imageProp][imageIndex];
如果图像位于images1或images2中,您可以通过以下方式轻松完成
let imageArray = resourcesObject[resourceIndex].images1 || resourcesObject[resourceIndex].images2;
将选择2中的任何一个,然后您可以使用imageArray
代替
答案 3 :(得分:0)
let resourcesObject = [
{
"author" : "photographer1",
"images1": ['cat1','cat2','cat3']
},
{
"author" : "photographer2",
"images2": ['dog1', 'dog2', 'dog3', 'dog4']
},
{
"author" : "photographer3",
"images3": ['rat1', 'rat2', 'rat3', 'rat4']
},
{
"author" : "photographer4",
"images4": ['bat1', 'bat2', 'bat3', 'bat4']
}
];
let obj=resourcesObject[Math.floor(Math.random() * resourcesObject.length)];
let value=Object.keys(obj)[1];
console.log(obj[value][Math.floor(Math.random() * obj[value].length)])