0

I'm trying to create an object that contains an array of objects. I'm using a jquery selector to determine the number of objects I want in the array. I'm having some issue here because when I enter the for loop Firefox says that "this.obj is undefined" I tried both the the this.obj = new Array() syntax as well as the this.obj[ ]; syntax.

function Base() {
    this.n = document.querySelectorAll('transform').length /3;
    this.obj = new Array(n); //array declaration
    for (var i = 0; i < this.n; i++) {
        this.obj[i] = new x3dSphere("b"+i); 
    }

}

I've only seen examples of arrays within objects that are declared like this.obj = [1,2,2,4] or the in the JSON form obj: [1,2,3,4]. I'm sure this is something really easy to do but I can't seem to find an example anywhere.

ryanmattscott
  • 321
  • 5
  • 17

2 Answers2

4

The following worked for me:

function Base() {
    this.n = 5;
    this.obj = [];
    for (var i = 0; i < this.n; i++) {
        this.obj.push(new Test());
    }
}

Where Test was:

var Test = function () {};

It seems like the real problem is that it never created this.obj because n was undefined. If you want to declare the array how you did before, try new Array(this.n).

EDIT

Would new Array(this.n) be faster than the this.obj=[] syntax since it's pre-allocated?

Interestingly enough, the answer is no.

Additionally, the accepted answer on this question has a great discussion of lots of other aspects of JavaScript array performance: What is the performance of Objects/Arrays in JavaScript? (specifically for Google V8)

I've updated my answer to use Array.push() because it is apparently much, much faster than doing Array[i] = new Obj() (shout out to Jason, who used it in his original answer).

Community
  • 1
  • 1
asmockler
  • 187
  • 7
  • Thanks, this worked for me I always seem to forget "this". Would `new Array(this.n)` be faster than the `this.obj=[]` syntax since it's pre-allocated? – ryanmattscott Jul 29 '15 at 03:41
  • Answer is actually no, surprisingly. Updated my answer with that and a few other goodies. – asmockler Jul 29 '15 at 08:19
3

You can declare an array with

this.obj = []; 

And then push objects into the array in a loop

for (var i =0; i < n; i ++) {
    this.obj.push(new x3dSphere ());
}
Jason
  • 15,915
  • 3
  • 48
  • 72