Question:
Show different ways to
iterate over an array of objects?
Answer
var arr = [{"name":"ofer",
"age":21},{"name":"ofer", "age":22},{"name":"ofer", "age":23},{"name":"ofer", "age":24},{"name":"ofer", "age":25}];
console.log("forIn:\n"); // For..In Loop
for(var i in arr)
console.log(arr[i].name + " " + arr[i].age);
console.log("foreach:\n"); //Foreach Loop; does not support break; Use every() instead;
arr.forEach(function(item){
console.log(item.name + " " + item.age);
});
console.log("for:\n"); // For Loop
for(var i = 0; i < arr.length; i++)
console.log(arr[i].name + " " + arr[i].age);
console.log("every:\n"); // Every Loop
arr.every(function(item){
console.log(item.name + " " + item.age);
return true
});
console.log("some:\n"); // Some Loop
arr.some(function(item){
console.log(item.name + " " + item.age);
});
console.log("forIn:\n"); // For..In Loop
for(var i in arr)
console.log(arr[i].name + " " + arr[i].age);
console.log("foreach:\n"); //Foreach Loop; does not support break; Use every() instead;
arr.forEach(function(item){
console.log(item.name + " " + item.age);
});
console.log("for:\n"); // For Loop
for(var i = 0; i < arr.length; i++)
console.log(arr[i].name + " " + arr[i].age);
console.log("every:\n"); // Every Loop
arr.every(function(item){
console.log(item.name + " " + item.age);
return true
});
console.log("some:\n"); // Some Loop
arr.some(function(item){
console.log(item.name + " " + item.age);
});
No comments:
Post a Comment