Search code examples
arraysloopsfor-loopforeachitems

For each loop with items from an array


Can anyone help me convert my current loop to a loop that does not contain an index or length. I need it to print the ages and names within the array. The loop I have worked as is but the instructions say to avoid using an index and length.

var personArray = [{ name: "Michael", age: 30 }, { name: "Gabriel", age: 21}, { name: "Caesar", age: 50 }];
  for (var i = 0; i < personArray.length; i++){
    writeToPage(personArray[i].name + " = "+ personArray[i].age);
  }

Solution

  • One option would be Array.forEach:

    const writeToPage = console.log;
    
    var personArray = [{ name: "Michael", age: 30 }, { name: "Gabriel", age: 21}, { name: "Caesar", age: 50 }];
    
    personArray.forEach(o => writeToPage(o.name + ' = ' + o.age));