1

I want to create/instantiate an array objectArray with several objects, whereby the objects shall contain x and y (empty at the beginning).

The length (amount of objects) of objectArray needs to be the same as the length of i.e. arrayLong. How I have to implement that?

Finally, it should look like that (etc. corresponding to the length of arrayLong):

var objectArray = [ { x: 0, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 0 } etc. ];
2
  • 2
    Create an empty array and add initialized objects in a loop. Commented Jul 2, 2014 at 13:02
  • Can you share your attempt(s) to implement? Commented Jul 2, 2014 at 13:03

1 Answer 1

3

Simple:

var objectArray = [];               // Declare the array variable
for(var i = 0; i < arrayLong; i++){ // Do something `arrayLong` times
    objectArray.push({x: 0, y:0});  // Add a object to the array.
}

This assumes arrayLong is a numeric value, of course.

Another way you could do it, is this:

var objectArray = Array.apply(null, Array(arrayLong))
                       .map(function(){return {x: 0, y:0}});
Sign up to request clarification or add additional context in comments.

1 Comment

Whoops, that should've been arrayLong, not 5 :P Thanks, though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.