我想知道如何在普通JavaScript中循环在数组内的多个对象。
下面的示例不起作用,我也不知道为什么。
<!DOCTYPE html>
<html>
<body style="background-color: #d89797;">
<h2>JavaScript Arrays</h2>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
<script>
var fruits, text, fLen, i;
fruits = [{
"customerID": "10",
"countInvoices": "42",
"name": "Xuseen"
},
{
"customerID": "100",
"countInvoices": "420",
"name": "khalid khalid"
}
];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
谢谢。
答案 0 :(得分:0)
Fruit[i]
是一个对象,因此您需要类似以下的内容:
var fruits, text, fLen, i;
fruits = [{
"customerID": "10",
"countInvoices": "42",
"name": "Xuseen"
},
{
"customerID": "100",
"countInvoices": "420",
"name": "khalid khalid"
}
];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i].customerID+ "|"+fruits[i].countInvoices+"|"+fruits[i].name + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
<h2>JavaScript Arrays</h2>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
答案 1 :(得分:0)
您需要添加需要打印出的阵列键。
此处更新了代码:
var fruits, text, fLen, i;
fruits = [{"customerID":"10", "countInvoices":"42", "name":"Xuseen"},
{"customerID":"100", "countInvoices":"420", "name":"khalid khalid"}];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>ID: " + fruits[i]['customerID'] + " countInvoices: "+fruits[i]['countInvoices']+" and NAME ="+fruits[i]['name']+" </li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
祝你好运。
答案 2 :(得分:0)
您还必须遍历数组内部的对象。
var fruits, text, fLen, i;
fruits = [{"customerID":"10",
"countInvoices":"42",
"name":"Xuseen"},
{"customerID":"100",
"countInvoices":"420",
"name":"khalid khalid"}];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
for (key in fruits[i]) {
text += "<li>" + key + ":" + fruits[i][key] + "</li>";
}
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
<h2>JavaScript Arrays</h2>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>