I have a JavaScript array of objects like this:
box[0] = {...}
box[1] = {...}
box[2] = {...}
...
box[499] = {...}
This objects are generated by the same constructor and added to the array inside a loop. The objects have methods in the prototype which need to know the object’s index in the array to do their stuff. Currently what I am doing is to set a property called id inside each object when I create it inside the loop, equal to the array index. Something like this:
box[i].id = i;
However I am not totally satisfied with this because each time I reorder the array using sort() I have to run a loop to update the id properties with the new index values.
My question is if there is a way to know inside an object its index in the array, without having to set the id property, hope you can help me.
Thanks in advance.
I don’t think a function inside an object in the Array is going to be aware of the index of the Array that is referencing it.
Because each item in the Array is simply pointing to that object in memory, there could conceivably be dozens of Array items, variables, Object properties, etc that reference that same object, so the function (or the object that contains the function) wouldn’t know which back reference you’re hoping to make.
I’m guessing you’ll be stuck doing what you’re doing if you need to know its index in the Array.
I suppose that function could call
indexOf()against the Array since it returns anindex, but that would require some overhead for each call, and you’ll need to added it for unsupported browsers.