9

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?

3
  • You can do a for (var item in myObjectHash) or for (var i = 0; i < myArray.length; i++) If you're working with actual arrays, don't use for...in.
    – Shmiddty
    Commented Sep 14, 2012 at 17:59
  • In recent versions of JS there is forEach otherwise you would have to do a for loop.
    – PeeHaa
    Commented Sep 14, 2012 at 17:59
  • In modern JS, for...of is the equivalent, not for...in: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jun 10, 2022 at 16:03

4 Answers 4

18

The closest construct is

a = { 2: 'Mike', 4: 'Peter', 7: 'Sam', 10: 'Michael' };
for(var n in a) {
    console.log(n+'='+a[n]);
}
7
  • BTW you have an object where OP has an array. You should not loop through an object like that unless you know what you are doing.
    – PeeHaa
    Commented Sep 14, 2012 at 18:06
  • 2
    @PeeHaa, the OP has a keyword 'array', but associative arrays are hardly arrays. And one shouldn't do anything unless one knows what one's doing :) Commented Sep 14, 2012 at 18:08
  • At least add if (a.hasOwnProperty(n)) when looping through an object in JS. :-)
    – PeeHaa
    Commented Sep 14, 2012 at 18:10
  • +1 - the answer could have had more of an explanation to what the code was doing, but his code is accurate and fine. haters gonna hate Commented Sep 14, 2012 at 18:11
  • Thanks, yes, the explanation could follow, but if I were to ask I'd do some research myself knowing the answer. On the other hand, obviously, the code was doing what the OP's code was doing :) Commented Sep 14, 2012 at 18:14
9

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]);
}
1
  • 1
    For the use of an extra library for something trivial as doing a loop.
    – PeeHaa
    Commented Sep 14, 2012 at 18:02
4

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

0
2

See below url

foreach equivalent of php in jquery?

Or try it

If you want to iterate an object, I would recommend the JavaScript variant:

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

You can also iterate objects in jQuery like this: Note! Doing this is pretty pointless unless you think this syntax is much simpler to maintain. The below syntax has much more overhead than the above, standard JavaScript, for-loop.

$.each(obj, function (key, value) {
    alert(key + ': ' + value);
});

To iterate arrays, this is how you do it in standard JavaScript (assuming arr is the array):

for (var i = 0, l = arr.length; i < l; i++) {
    alert(i + ': ' + arr[i]);
}

To do it in jQuery, you can do it like this:

$.each(arr, function (index, value) {
    alert(index + ': ' + value);
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.