Just to go through all and show, is usually used the foreach.
In the case of map it could be used, however it is usually used to create a new array resulting from the change of the array in question.
In the case of forEach
and of map
, it is called with a function, the first parameter being the "pointer", or current value, the second parameter is the index of the array in question (optional parameter), and the third parameter (also optional) is the array itself, so it can be:
students.map(function (student, index, arr) {
console.log(student.name);
console.log(student.grade);
console.log(index);
console.log(arr);
});
students.forEach(function (student, index, arr) {
console.log(student.name);
console.log(student.grade);
console.log(index);
console.log(arr);
});
In ES6 mode, in which case it is not necessary the optional parameters, only to list the data would be like this, with forEach
and map
:
var students = [
{
name: 'Anna',
grade: 6
},
{
name: 'John',
grade: 4
},
{
name: 'Maria',
grade: 9
}
];
// for(var i = 0; i < students.length; i++){
// console.log(students[i].name);
// console.log(students[i].grade);
//}
students.forEach(student => {
console.log(student.name);
console.log(student.grade);
});
students.map(student => {
console.log(student.name);
console.log(student.grade);
});