Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through elements of an array in Javascript [duplicate]

I have an array in Javascript:

var array = new array();
array[0] = "apples";
array[1] = "oranges";
array[2] = "pears";

In PHP, with a given array, I can use the following to loop through an array, and break up the keys and values:

foreach ($array as $key => $value) {
    echo("Key is $key and Value is $value");
}

How can I do this in Javascript? I'm aware of:

for (x in array){
    // Do something with x.
}

But I've found nothing that will replicate the php style foreach. Is it possible to concisely achieve something similar in Javascript? (I'm also using jQuery, if something can be done in jQuery).

like image 925
EvilChookie Avatar asked Jul 14 '09 22:07

EvilChookie


People also ask

Can array have duplicate values JavaScript?

With ES6, we have a javascript Set object which stores only unique elements. A Set object can be created with array values by directly supplying the array to its constructor. If the array has duplicate values, then they will be removed by the Set. This means that the Set will only contain unique array elements.

How do you duplicate elements in an array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

Can you loop through an array in JavaScript?

If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array. In the loop above, we first initialized the index number so that it begins with 0 .


2 Answers

First,

var array=[];

is preferable to using "new."

Second, your keys are numeric in this case, so you just do:

for (i=0;i<array.length;i++) {
  console.log("Key is "+i+" and Value is "+array[i]);
}

If you want to have keys that aren't numeric, use a JavaScript object instead of an array. It's valid to use strings instead of numbers as array indexes, but JavaScript doesn't have much support for that.


I use "console.log" because I assume you don't want a bunch of alerts popping up. console.log could be replaced with whatever you use to log info. You could use alert() or write text into a div instead.

like image 95
Nosredna Avatar answered Nov 03 '22 21:11

Nosredna


Using jQuery.each you could write something similar to (not tested):

jQuery.each(array, function(k,v) {
    console.log("K: "+,k," V:",v);
});
like image 38
Grzegorz Oledzki Avatar answered Nov 03 '22 20:11

Grzegorz Oledzki