Possible Duplicate:
Functional approach to basic array construction
I am new to js. I just want to know which one is the right approach. Below I have posted my code.
var doubles = (i*20 for (i in it));
var doubles ={i*20 for (i in it)};
Thanks
Possible Duplicate:
Functional approach to basic array construction
I am new to js. I just want to know which one is the right approach. Below I have posted my code.
var doubles = (i*20 for (i in it));
var doubles ={i*20 for (i in it)};
Thanks
You should use ordinary for loops when iterating over arrays. for...in is used for iterating over object properties.
So, the correct way is:
for (var i = 0; i < array.length; ++i) {
// do something
}
To iterate over object properties:
for (var prop in obj) {
// do something with prop
}
Assuming it
is an array, you can use .map()
:
var doubles = it.map(function(i){ return i*20; });
Also you might want to have a look at how to write List/Array comprehensions in JavaScript
Assuming you want to use Mozilla's Generator expressions (where it
is an existing Iterator
), you need to use square brackets:
var twentyfolds = [i*20 for (i in it)];
For future reference, ECMAScript 6 (aka Harmony) will most likely introduce a new sane way of iterating over objects (arrays included):
for(var x of array) {
// do something with x
}
It will also introduce array comprehensions and generator expressions to the core language:
var arr = [1, 2, 3];
console.log([i*20 for (i of arr)])
Both of these options are syntax errors. If 'it' is a list, then you can iterate through it with a for loop or the forEach method. In your case however, it looks like you are really looking for the map method.
var doubles = it.map(function (i) { return i * 20; });