About half of all web surfers (starting from this record, the number is constantly growing) use browsers that support ECMAScript5 (for example, 5th edition), which has several new designs for this, including forEach :
"one two three".split(" ").forEach(function(val, key) {
(Or, if you do not need the key variable, just leave it (e.g. ...forEach(function(val) {... ).)
Even if the browser does not have it, forEach is one of those functions that can be “customized” (emulated) completely correctly even in older browsers, for example. via es5_shim.js or the like. So just turn on the gasket (or write it yourself) and happily use it regardless of its support or addition. Or you can use a library that already provides its or its analogue (jQuery has $.each , Prototype adds each to arrays, Backbone offers something similar, etc.).
forEach also has the advantage that loop-dependent variables ( entry and index ) are contained in an iterator function, so you don't pollute the area in which you use it. There is a time cost because you have a function overhead for each element of the array. But function calls are very fast in real terms ( even on IE6 , which is a dog), you can be sure that everything you do in the body of the circuit completely washed out the extra overhead.
Nothing is embedded in the "old" version of JavaScript (3rd edition), you either provide your own function for this, or in each loop you declare a variable for the array (as well as an indexing variable and an array input variable), for example:
var array = "one two three".split(" "); var key, val; for (key = 0; key < array.length; ++key) { val = array[key];
But again, you could provide your own forEach quite easily.
Another construct that you can use in both older and newer versions is for..in , which for..in over the enumerated properties of the object. However, you still need all the variables. Since this means more than just “indexes,” you should add some precautions:
var array = "one two three".split(" "); var key, val; for (key in array) { if (array.hasOwnProperty(key) && String(Number(key)) === key) {
... but in this case he does not buy anything. This is useful when the array is sparse (for example, has large spaces in it).