我想显示从数组中随机选择的对象的对象属性(标签,图标,Href)。我应该怎么做,这就是我到目前为止所拥有的。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var myArray = [{
label: "Pears",
icon: "Pears.png",
href: "./Pears"
}, {
label: "Appels",
icon: "Appels.png",
href: "./Appels"
}, {
label: "Mango",
icon: "Mango.png",
href: "./Mango"
}, ];
var randomItem1 = myArray[Math.floor(Math.random()*myArray.length)];
var randomItem2 = myArray[Math.floor(Math.random()*myArray.length)];
var randomItem3 = myArray[Math.floor(Math.random()*myArray.length)];
var randomItem4 = myArray[Math.floor(Math.random()*myArray.length)];
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("randomItem1").innerHTML = randomItem1;
document.getElementById("randomItem2").innerHTML = randomItem2;
document.getElementById("randomItem3").innerHTML = randomItem3;
document.getElementById("randomItem4").innerHTML = randomItem4;
});
</script>
<p>Random 1</p>
<div id = "randomItem1"> </div>
<!--Label value-->
<!--Icon value-->
<!--Href value-->
<p>Random 2</p>
<div id = "randomItem2"> </div>
<p>Random 3</p>
<div id = "randomItem3"> </div>
<p>Random 4</p>
<div id = "randomItem4"> </div>
</body>
</html>
答案 0 :(得分:1)
只需使用其对象键,例如
randomItem1.label
randomItem1.icon
randomItem1.href
堆栈片段
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var myArray = [{
label: "Pears",
icon: "Pears.png",
href: "./Pears"
}, {
label: "Appels",
icon: "Appels.png",
href: "./Appels"
}, {
label: "Mango",
icon: "Mango.png",
href: "./Mango"
}, ];
var randomItem1 = myArray[Math.floor(Math.random()*myArray.length)];
var randomItem2 = myArray[Math.floor(Math.random()*myArray.length)];
var randomItem3 = myArray[Math.floor(Math.random()*myArray.length)];
var randomItem4 = myArray[Math.floor(Math.random()*myArray.length)];
document.addEventListener("DOMContentLoaded", function(event) {
// grabbed all keys in this first assignment to show how-to
document.getElementById("randomItem1").innerHTML = randomItem1.label + " : " +
randomItem1.icon + " : " +
randomItem1.href;
document.getElementById("randomItem2").innerHTML = randomItem2.label;
document.getElementById("randomItem3").innerHTML = randomItem3.label;
document.getElementById("randomItem4").innerHTML = randomItem4.label;
});
</script>
<p>Random 1</p>
<div id = "randomItem1"> </div>
<!--Label value-->
<!--Icon value-->
<!--Href value-->
<p>Random 2</p>
<div id = "randomItem2"> </div>
<p>Random 3</p>
<div id = "randomItem3"> </div>
<p>Random 4</p>
<div id = "randomItem4"> </div>
</body>
</html>