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.
About the Author
The author has not added a profile short description yet.
Show Profile
Related Topics
Windows Batch Script: Computer Shutdown
Tutorial | 2 Comments
JavaScript: Create and Use Arrays
Info | 0 Comments
PHP: Remove all empty elements from string array
Tip | 0 Comments
Send Form Input as an Array to PHP Script
Tip | 0 Comments
Lazarus: Load File as Byte Array and save Byte Array as File
Tutorial | 0 Comments
PHP: Write array to individual Variables
Tutorial | 0 Comments
JavaScript: Sort Array of Numbers
Tutorial | 0 Comments
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.