This article listed various way to implement "foreach" in JavaScript and introduced very clear.
If you want to find simplified explanation, you can read this article instead.
I personally prefer to use "for-in" loop, let's see examples on array and object.
If you want to find simplified explanation, you can read this article instead.
I personally prefer to use "for-in" loop, let's see examples on array and object.
Using for-in to loop through an array
var arr = ['val1','val2','val3'];
for (var key in arr)
{
console.log(key+' => '+arr[key]);
}
//0 => val1
//1 => val2
//2 => val3
Using for-in to loop through an object
var obj = {'key1':'val1','key2':'val2','key3':'val3'};
for (var key in obj)
{
console.log(key+' => '+obj[key]);
}
//key1 => val1
//key2 => val2
//key3 => val3
Using for-in to loop through objects inside an array
var arr = [
{'key11':'val11','key12':'val12','key13':'val13'},
{'key21':'val21','key22':'val22','key23':'val23'}
];
for (var key1 in arr)
{
console.log(key1+' => '+arr[key1]);
for (var key2 in arr[key1])
{
console.log(key2+' => '+arr[key1][key2]);
}
}
//0 => [object Object]
//key11 => val11
//key12 => val12
//key13 => val13
//1 => [object Object]
//key21 => val21
//key22 => val22
//key23 => val23
Comments
Post a Comment