Q:

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

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?

A:

The closest construct is
a = { 2: 'Mike', 4: 'Peter', 7: 'Sam', 10: 'Michael' };
for(var n in a) {
    console.log(n+'='+a[n]);
}

A:

In JQuery, The $.each function is similar.
It allows you to iterate arrays using a callback function where you have access to each item:
var arr = ["one", "two", "three", "four", "five"];
$.each(arr, function(index, value) {
  // work with value
});

For plain Javascript?
for (var key in obj) {
    alert(key + ': ' + obj[key]);
}

A:

For you exists two way.
First when data is in object (in example it is in my_list)
and second when data is exactly in array (in example it is my_array)
In any case you can use JavaScript For...In statement
Example:
<script type="text/javascript" charset="utf-8">
    var data;
    var my_list  = {2:'Mike', 4:'Peter', 7:'Sam', 10:'Michael'};
    var my_array = new Array();
    my_array[2]  = 'Mike';
    my_array[4]  = 'Peter';
    my_array[7]  = 'Sam'; 
    my_array[10] = 'Michael';

    data = '';
    for(index in my_list) {
        data += (index+'='+my_list[index]+"\n");
    }
    console.log(data);

    data = '';
    for(index in my_array) {
        data += (index+'='+my_array[index]+"\n");
    }
    console.log(data);
</script>

In both cases console output will be:
2=Mike
4=Peter
7=Sam
10=Michael

Actually please read http://www.w3schools.com/js/js_loop_for_in.asp

