开发者

How to get the index of an object inside an array of objects?

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 t开发者_C百科o 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 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


Why don't you add a unique property on each object and use that property to lookup the indexOf that Object.

If you have a constructor you can add an _id and then lookup that id using:

function getIndex(box, objectId) {
   var index = box.map(function(e) { return e._id; }).indexOf(objectId);
   return index;
}

This will work even if you sort the array, but you need to keep the id unique.

Array.prototype.map is not available on IE7 or IE8. ES5 Compatibility

btw, I don't like this solution but it will work on your problem :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜