javascript - 显示对象属性
问题描述
我想从数组中随机选择的对象中显示对象属性(标签、图标、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>
推荐阅读
- reactjs - 每个孩子都应该有一个道具警告
- python - django fullcalender refetching events not workig
- java - 如何在与spring boot交互的android studio中进行登录活动?
- c++ - 部分输入验证
- r - 将 CSV_file 从桌面导入到 R
- python - 如何在我的 GPU 上运行此功能?(Python)
- xamarin.forms - 如何访问复选框和过滤数据
- c - c中var的地址是按值传递的吗?
- python - 如何从多个 csv 文件中获取每 X 行的列的平均值
- tensorflow - 如何让 Google Cloud AI Platform 在训练期间检测 `tf.summary.scalar` 调用?