javascript - Can you add an object to an array inside its constructor -


i'm trying add objects array specific id need know inside constructor. 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 line in question. } 

obviously example. in real code i'm using id in id of 3 new dom objects, need have available inside constructor.

if id number work, arrays meant accessed index. see time in code , being in constructor not matter long objectarray declared globally:

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

if id not number working object.

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

here example using 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 line in question. }  newobject("kevin", "30", "blue"); alert(objectarray[3].name); 

one thing note this, if calculated id not in sync actual array, assign object third index when array empty, array.length return 4 array contains 1 element.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -