我目前正在学习javascript。我想问一下用循环打印所有数组元素。我应该使用什么样的循环/条件?任何人都可以给我一个片段/示例如何做到这一点? 谢谢。
var newObj = [
{
id : "1",
name: "one"
},
{
id : "2",
name: "two"
},
{
id : "3",
name: "three"
},
{
id : "4",
name: "four"
},
{
id : "5",
name: "five"
},
]
console.log(newObj);
window.onload = function ()
{
var x;
x = newObj[0].name;
//x = newObj[0].id;
document.getElementById("id").innerHTML = x;
};
<!DOCTYPE html>
<html>
<head>
<script src="1.js"></script>
</head>
<body>
<h3 align="center" id="id"></h3>
</body>
</html>
答案 0 :(得分:1)
JavaScript支持a for...of
loop。在你的情况下,循环可能看起来像这样:
for (obj of newObj)
results += obj.name + " "
document.getElementById("id").innerHTML = results;
答案 1 :(得分:1)
循环遍历数组中的每个对象:
newObj.forEach(function (item) {
// print the object
console.log(item);
// print each object property individually
for (var key in item) {
console.log(key, ':', item[key]);
}
});
答案 2 :(得分:1)
我最喜欢的方法是这个,但只是因为我对它感到满意。
var newObj = [ { id : "1", name: "one" }, { id : "2", name: "two" }, { id : "3", name: "three" }, { id : "4", name: "four" }, { id : "5", name: "five" }, ]
for(var i=0; i<newObj.length; i++){
console.log(newObj[i].id + ': ' + newObj[i].name);
}
答案 3 :(得分:1)
我认为w3schools here提供的示例应该对您有所帮助。他们通过循环来创建不同大小的标题。
以下是修改后的代码。
window.onload = function () {
var x = '';
for (let i = 0; i < newObj.length; i++) {
x = x + "<h2>"+ newObj[i].name + "</h2>";
}
document.getElementById("demo").innerHTML = x;
};
答案 4 :(得分:1)
map()是一个很好的函数,用于迭代数组。
newObj.map((o)=> {
document.write('id:'+o.id+' '+'name:'+o.name);
});
这很棒,因为你可以像这样直接将它链接到你的数组
var newObj = [
{
id : "1",
name: "one"
},
{
id : "2",
name: "two"
},
{
id : "3",
name: "three"
},
{
id : "4",
name: "four"
},
{
id : "5",
name: "five"
},
].map((o)=> {
document.write('id:'+o.id+' '+'name:'+o.name);
});
答案 5 :(得分:1)
在ES2017(现代JavaScript)中:
newObj.forEach((obj) => {
console.log(obj); // log each object in the array
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key}: ${value}`); // log each value in each object
});
});
细分:
答案 6 :(得分:1)
如果您希望写入HTML文档(正如您的一些评论所暗示的那样):
const newObj = [
{
id : "1",
name: "one"
},
{
id : "2",
name: "two"
},
{
id : "3",
name: "three"
},
{
id : "4",
name: "four"
},
{
id : "5",
name: "five"
},
]
const element = document.getElementById("id");
newObj.forEach((obj) => {
Object.entries(obj).forEach(([key, value]) => {
element.innerHTML+=(`<p>${key}: ${value}</p>`); // write each key-value pair as a line of text
});
element.innerHTML+=('<br>'); // add another line break after each object for better readability
});
<div id='id'></div>