简体   繁体   中英

Can you add an object to an array inside its constructor

I'm trying to add objects to an array with a specific id which I need to know inside the constructor. Will this work?

objectArray = [];
function newObject (name, age, eyeColour) {
this.name = name;
this.age = age;
this.eyeColour = eyeColour;
var id = *some integer* 
this.id = id;
objectArray[id] = this;    //This is the line in question.
}

Obviously this is just an example. In my real code I'm using the id in the id of 3 new DOM objects, so I need to have it available inside the constructor.

If id is a number this will definitely work, arrays are meant to be accessed by their index. You see this all the time in code and being in a constructor will not matter as long as objectArray is declared globally:

var arr = ["one", "two"];

for(var i =0; i < arr.length; i++){
   alert(arr[i]);
}

If the id is not a number your most likely working with an object.

var obj = {one: 1, two: 2};
alert(obj["one"]);

Here is an example using your code:

var objectArray = []

function newObject (name, age, eyeColour) {
    this.name = name;
    this.age = age;
    this.eyeColour = eyeColour;
    var id = 3
    this.id = id;
    objectArray[id] = this;    //This is the line in question.
}

newObject("Kevin", "30", "Blue");
alert(objectArray[3].name);

One thing to note about this, if your calculated id is not in sync with the actual array, so say you assign the object to the third index when the array is empty, array.length will return 4 however the array only contains 1 element.

Yes, this works. But you should probably define your id - you are missing the keyword var . If id is not a number, but a string, it will work if you define the objectArray as an Object. (not an Array)

I'm not sure, where you defined your ObjectArray. But if you put the line var ObjectArray = {}; above, it will work. (If you're sure, that id is always a number, use var ObjectArray = []; instead.

This is the resuting code:

function newObject (name, age, eyeColour) {
    this.name = name;
    this.age = age;
    this.eyeColour = eyeColour;
    var id = *something calculated*
    this.id = id;
    var objectArray = {};   //or =[] for and Array
    objectArray[id] = this;    //This is the line in question.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM