Reputation: 259
I'm trying to initialize an array with self-invoking function, assume for simplicity as an example, that initial values are squares of numbers from 0 to 4. The new
keyword creates new object, so one can access fields of newly created object with this.x
or this[x]
inside the IIFE body, following the new
keyword. The code is:
var arr = new (function() {
for (var i=0; i<5; i++) { this[i]=i*i; }
})();
Now, you can access corresponding fields of variable arr
like arr[4]
, and get 16
. That's perfectly fine if you only work with arr
like with an object, but once you try to treat it like an array, you have a problem. Namely, you can't apply functions like reduce
to it:
< arr.reduce(...);
> TypeError: arr.reduce is not a function
That's because arr
is really an object, not an array:
< arr;
> ({0:0, 1:1, 2:4, 3:9, 4:16})
So here is my question: how to avoid such behavior within this method? How to make JavaScript interpret this newly created object as an array?
Upvotes: 2
Views: 2514
Reputation: 665456
Without the IEFE it is shorter and more clear:
var arr = [];
for (var i=0; i<5; i++) arr[i] = i*i;
Without the additional counter variable i
, you could do:
for (var arr=[]; arr.length<5; ) arr[arr.length] = Math.pow(arr.length, 2);
Upvotes: 3
Reputation: 114579
You don't need to use the new
keyword for that...
var arr = (function() {
var x = [];
for (var i=0; i<4; i++)
x.push(i*i);
return x;
})();
the new
keyword creates an object and sets its constructor, then binds this
to it and calls the function. You don't need anything of that except calling the function, so just do so.
Upvotes: 3