Possible Duplicate:
Loop through array in JavaScript
I want to make the equivalent of php's foreach in javascript. Because I don't really know the Javascript language, I'd like someone to rewrite this PHP code into the Javascript piece:
$my_array = array(2 => 'Mike', 4 => 'Peter', 7 => 'Sam', 10 => 'Michael');
foreach($my_array as $id => $name)
{
echo $id . ' = ' . $name;
}
Is that even possible to do in the Javascript language?
The map method is very similar to the forEach method—it allows you to execute a function for each element of an array. But the difference is that the map method creates a new array using the return values of this function. map creates a new array by applying the callback function on each element of the source array.
The every() function is a good alternative to forEach, let us see an example with a test implementation, and then let's return out of the every() function when a certain condition meet.
forEach Loop It is faster in performance. It is slower than the traditional loop in performance. The break statement can be used to come out from the loop. The break statement cannot be used because of the callback function.
C# foreach loop is used to iterate through items in collections (Lists, Arrays etc.). When you have a list of items, instead of using a for loop and iterate over the list using its index, you can directly access each element in the list using a foreach loop.
The closest construct is
a = { 2: 'Mike', 4: 'Peter', 7: 'Sam', 10: 'Michael' };
for(var n in a) {
console.log(n+'='+a[n]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With