Цhat is the most effective way to find an element position within an array, if we got access to the element itself?
var arr 开发者_开发百科= [];
for (var i = 0; i < 10; i++) {
arr[i] = {test: Math.floor(Math.random() * 101)}
}
var test = arr[Math.floor(Math.random() * 11)];
Now how can I get the position of the element that test
refer to?
I'd just store the position when generating it here, like this:
var arr = [];
for (var i = 0; i < 10; i++) {
arr[i] = {test: Math.floor(Math.random() * 101)}
}
var index = Math.floor(Math.random() * 11);
var test = arr[index];
//index is the position
I assume that the random generation is just an example.
Now if you've got a reference to an element and want to find out its index you can use Array.indexOf
method. It's a new feature so not all browsers support it natively, but it's easy to implement. A bare-bone solution would look like:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement) {
var len = this.length >>> 0;
for (var i = 0; i < len; i++) {
if (searchElement === this[i]) return i;
}
return -1;
};
}
Now you can use it as:
index = array.indexOf(elem) // index from an element reference
examp = [5,8,12,5].indexOf(12) // 2
精彩评论