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.

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Answer is actually no, surprisingly. Updated my answer with that and a few other goodies.
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 ());
}

Comments

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.