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?

Community
  • 1
  • 1
Sapp
  • 624
  • 2
  • 7
  • 13
  • 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 Sep 14 '12 at 17:59
  • In recent versions of JS there is [`forEach`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach) otherwise you would have to do a `for` loop. – PeeHaa Sep 14 '12 at 17:59
  • In modern JS, `for...of` is the equivalent, not `for...in`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of – still_dreaming_1 Jun 10 '22 at 16:03

4 Answers4

18

The closest construct is

a = { 2: 'Mike', 4: 'Peter', 7: 'Sam', 10: 'Michael' };
for(var n in a) {
    console.log(n+'='+a[n]);
}
Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
  • 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 Sep 14 '12 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 :) – Michael Krelin - hacker Sep 14 '12 at 18:08
  • At least add `if (a.hasOwnProperty(n))` when looping through an object in JS. :-) – PeeHaa Sep 14 '12 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 – Snuffleupagus Sep 14 '12 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 :) – Michael Krelin - hacker Sep 14 '12 at 18:14
  • @PeeHaa and Michael you still have to perform some form of validation for an array as well as an object, otherwise this will screw up if you extend `Array.prototype`. At the very least `typeof a[n] !== 'function'`, unless it is an array of functions, then you need to get cleverer. – DaveRandom Sep 14 '12 at 22:22
  • @DaveRandom, it's not an array ;-) And yes, the OP is supposed to figure out a thing or two about the construct he's just learned. I'm sure he's aware of that. – Michael Krelin - hacker Sep 15 '12 at 08:26
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]);
}
evanhutomo
  • 627
  • 1
  • 11
  • 24
dsgriffin
  • 66,495
  • 17
  • 137
  • 137
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

xiaose
  • 616
  • 1
  • 7
  • 19
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);
});
Community
  • 1
  • 1
Abid Hussain
  • 7,724
  • 3
  • 35
  • 53