00 Votes

JavaScript: Run through array element by element (foreach)

Tip by Progger99 | 2012-03-15 at 18:14

Sometimes, we have to go through an array element by element in JavaSript. Unfortunately, JavaScript do not knows a foreach command as we have, for example, in PHP. But the following code snippet can help us to exactly do that:

var arr = [1,2,3,4];
var s   = '';
 
for (var i=0; i<arr.length; i++) {
   s = s + arr[i];
}
 
alert(s); //output: '1234'

In the example, first, we fill an array with four numbers and we define an empty string. After that, we go trough the array from i=0 to the length of the array with í < arr.length. In the loop, we attach the current element of the arry arr[i] to the string. The output in the last line is accordingly '1234'.

Tip: What we have shown in the example, you can also easily achieve with the function join(). The code arr.join('') would return the same string, that our for loop has stored in the string s. Join() also allows to pass a character as a parameter which should be written between the individual elements of the array. For example, with arr.join(',') we get the elements of the array separated with a comma.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Foreach Loop in Lazarus?

Question | 1 Answer

jQuery: Replace element

Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.