Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make simple php's foreach equivalent in Javascript? [duplicate]

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?

like image 766
Sapp Avatar asked Sep 14 '12 17:09

Sapp


People also ask

What can I use instead of forEach in JavaScript?

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.

What is an alternative to forEach?

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.

Which is faster forEach or for loop JavaScript?

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.

How do you use forEach instead of for loop?

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.


1 Answers

The closest construct is

a = { 2: 'Mike', 4: 'Peter', 7: 'Sam', 10: 'Michael' };
for(var n in a) {
    console.log(n+'='+a[n]);
}
like image 116
Michael Krelin - hacker Avatar answered Oct 29 '22 18:10

Michael Krelin - hacker