3

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

Community
  • 1
  • 1
minhaz
  • 503
  • 1
  • 5
  • 12

4 Answers4

4

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
}
Davorin
  • 1,160
  • 15
  • 31
  • How do you know `it` is not an object? :-) – Bergi Nov 11 '12 at 13:54
  • @Bergi you don't really know, an array is an object. So if you pass an array to the `for in` it may iter over indexes and other keys. That said, if you pass an object to a function you should expect and object to be passed to the for. If you don't know what's getting into your function, it's a different story. – Loïc Faure-Lacroix Nov 11 '12 at 13:58
  • I don't. It was an assumption ;) – Davorin Nov 11 '12 at 13:59
  • @Davorin ,It is object. Your code solves my problem but I want to know that how to do it in my way if possible. Just curisity! – minhaz Nov 11 '12 at 14:14
  • @minhaz, I don't think it is possible in pure JS, you should try CoffeeScript if you want to use _comprehensions_. – Davorin Nov 11 '12 at 15:22
2

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)];
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

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)])
lqc
  • 7,434
  • 1
  • 25
  • 25
0

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; });
AHM
  • 5,145
  • 34
  • 37