最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to print all javascript array elements with looping? - Stack Overflow

programmeradmin1浏览0评论

i'm currently learning about 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>

i'm currently learning about 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>

Share Improve this question edited Oct 27, 2017 at 2:15 Wira Xie asked Oct 27, 2017 at 2:11 Wira XieWira Xie 8395 gold badges24 silver badges46 bronze badges 3
  • 2 there's no JSON ... you have a javascript array called newObj – Jaromanda X Commented Oct 27, 2017 at 2:11
  • 1 my bad, i will edit it – Wira Xie Commented Oct 27, 2017 at 2:12
  • From the code in your question you seem to know that newObj[0] will give you the first array element, and newObj[0].name will give you that element's name. Combine that with a basic for loop using the loop counter instead of the hard-coded 0 and Bob's your uncle - not necessarily the best solution, but one that you should study till you understand it. I would be surprised if introductory JS tutorials didn't cover using a loop with an array. – nnnnnn Commented Oct 27, 2017 at 2:50
Add a ment  | 

7 Answers 7

Reset to default 1

JavaScript supports a for...of loop. 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]);
    }
});

I think the example presented at w3schools, here, should be helpful to you. 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.

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

If you're looking to write to your HTML document (as some of your ments imply):

 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>

In ES2017 (modern 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:

  • Array.prototype.forEach()

  • Object.entries()

  • Array destructuring

  • Template literals

My favorite approach is this one, but only because I've gotten fortable 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);
}
发布评论

评论列表(0)

  1. 暂无评论