Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  62] [ 5]  / answers: 1 / hits: 69496  / 13 Years ago, fri, december 30, 2011, 12:00:00

I am wondering if JavaScript has an enhanced for loop syntax that allows you to iterate over arrays. For example, in Java, you can simply do the following:



String[] array = hello there my friend.split( );

for (String s : array){
System.out.println(s);
}


output is:



hello
there
my
friend


Is there a way to do this in JavaScript? Or do I have to use array.length and use standard for loop syntax as below?



var array = hello there my friend.split( );

for (i=0;i<array.length;i++){
document.write(array[i]);
}

More From » for-loop

 Answers
117

JavaScript has a foreach-style loop (for (x in a)), but it is extremely bad coding practice to use it on an Array. Basically, the array.length approach is correct. There is also a a.forEach(fn) method in newer JavaScripts you can use, but it is not guaranteed to be present in all browsers - and it's slower than the array.length way.


EDIT 2017: "We'll see how it goes", indeed. In most engines now, .forEach() is now as fast or faster than for(;;), as long as the function is inline, i.e. arr.forEach(function() { ... }) is fast, foo = function() { ... }; arr.forEach(foo) might not be. One might think that the two should be identical, but the first is easier for the compiler to optimise than the second.


Belated EDIT 2020: There is now for (const item of iterable), which solves the downsides of using for (item in iterable).


[#88312] Wednesday, December 28, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grant

Total Points: 169
Total Questions: 96
Total Answers: 98

Location: Cape Verde
Member since Sat, Apr 24, 2021
3 Years ago
;