简体   繁体   English

如何使用循环打印所有javascript数组元素?

[英]How to print all javascript array elements with looping?

i'm currently learning about javascript. 我目前正在学习JavaScript。 I wanted to ask about printing all array elements with looping. 我想问一下有关循环打印所有数组元素的问题。 What kind of loop/condition i should use? 我应该使用哪种循环/条件? can anyone give me a snippet/example how to do it? 谁能给我一个片段/示例怎么做? thank you. 谢谢。

  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> 

JavaScript supports a for...of loop . JavaScript支持for...of循环 In your case, the loop could look something like this: 在您的情况下,循环可能看起来像这样:

for (obj of newObj)
  results += obj.name + " "

document.getElementById("id").innerHTML = results;

To loop over each object in the array: 要遍历数组中的每个对象:

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]);
    }
});

My favorite approach is this one, but only because I've gotten comfortable with it. 我最喜欢的方法是这种方法,但这只是因为我已经习惯了。

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);
}

I think the example presented at w3schools, here , should be helpful to you. 我认为, 这里的 w3schools上提供的示例应该对您有所帮助。 They have looped to create headings of different sizes. 它们循环创建不同大小的标题。

Here is a modified code for you. 这是为您修改的代码。

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;
};

map() is a great function to use to iterate over arrays. map()是用于迭代数组的强大功能。

newObj.map((o)=> { 
    document.write('id:'+o.id+' '+'name:'+o.name);
});

it's great because you can chain it straight off your array like this 这很棒,因为您可以像这样直接将其链接到数组

 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);
});

In ES2017 (modern JavaScript): 在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
    });
});

Breakdown: 分解:

If you're looking to write to your HTML document (as some of your comments imply): 如果您要写入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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM