Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  103] [ 3]  / answers: 1 / hits: 40052  / 14 Years ago, fri, january 21, 2011, 12:00:00

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.


More From » arrays

 Answers
143

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 an index, but that would require some overhead for each call, and you'll need to added it for unsupported browsers.



theArr.indexOf( this ); // assuming the function was called from the context
// of the object in question

[#94115] Wednesday, January 19, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sherryd

Total Points: 254
Total Questions: 92
Total Answers: 89

Location: Equatorial Guinea
Member since Sun, Feb 14, 2021
3 Years ago
;