0

I want to create 10 Fly objects in a functional manner. I thought this would work:

var flies = new Array(10).map(function() {
    return new Fly();
});

It doesn't. It creates an array of length ten with undefined as their values.

How can I create 10 objects without using for(var i = 0; i < 10; i++)...?

EDIT: This is an academic exercise for the sake of learning only. It's find if a for is used under the hood. I'm just trying to figure out what JavaScript can do.

8
  • 4
    Array.apply(0, Array(10)).map Commented Oct 8, 2014 at 20:13
  • 1
    May you enlighten us on why wouldn't you use for ? Commented Oct 8, 2014 at 20:15
  • 1
    [0,1,2,3,4,5,6,7,8,9].map - if you're dead set against for Commented Oct 8, 2014 at 20:15
  • 2
    Read the docs for array.map: callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes that are undefined, those which have been deleted or which have never been assigned values. Commented Oct 8, 2014 at 20:16
  • 1
    In ES6 you'll be able to do: Array.from({length: 10}, _ => new Fly()); Commented Oct 8, 2014 at 20:19

2 Answers 2

2

Out of the box, there is only @elcanrs way. If you use a library such as Underscore you could use http://underscorejs.org/#times

var flies = _.times(10, function(){return new Fly()})
Sign up to request clarification or add additional context in comments.

6 Comments

Guess what _.times uses to do this? Yep! A for: for (var i = 0; i < n; i++) accum[i] = iteratee(i); :-D
Actually they use Array for creating an accumulator and then _.iteratee which uses more calls that a for() for sure underscorejs.org/docs/underscore.html
I was just pointing out that the OPs restriction to not use for is silly since any other solution will probably just use it internally.
Indeed, in JavaScript the best way may be a for not a _.times.
@RocketHazmat: once we get TCO we won't need to use loops anymore! yay
|
1

I'm pretty sure that any fancy approach will be using a for, or another loop, at a lower level... If you reeeealy want to get rid of this, you can work with a recursive approach and create your own Fly Factory function!

Honestly, IMO it's a waste of effort. But at least it has not for loop! =D

function Fly() {
}

function CreateFlies(n) {
    var arr = [new Fly()];
    arr = (n > 1 ? arr.concat(CreateFlies(n-1)) : arr);
    return arr;
}
var flies = CreateFlies(10);
alert(flies);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.