gpt4 book ai didi

javascript - 显示对象属性

转载 作者:行者123 更新时间:2023-12-03 01:32:28 26 4
gpt4 key购买 nike

我想显示从数组中随机选择的对象的对象属性(标签、图标、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>

最佳答案

只需使用他们的对象键,例如

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>

关于javascript - 显示对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51227557/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com