You can use map
, which is a functional programming technique that's also available in other languages like Python, and Haskell.
[1,2,3,4].map( function(item) {
alert(item);
})
The general syntax is:
array.map(func)
In general func
would take one parameter, which is an item of the array. But in the case of JavascriptJavaScript, it can take a second parameter which is the item's index, and a third parameter which is the array itself.
The return value of array.map
is another array, so you can use it like this:
var x = [1,2,3,4].map( function(item) { return item * 10; } );
And now x is [10,20,30,40]
.
You don't have to write the function inline. It could be a separate function.
var item_processor = function(item) {
// doDo something complicated to an item
}
new_list = my_list.map(item_processor);
which would be sort-of equivalent to:
for (item in my_list) { item_processor(item); }
exceptExcept you don't get the new_list
.