Given a javascript array and one of its members, how do I get the member index?
3 answers
You need to call indexOf
, for example:
var index = someArray.indexOf(value);
Since IE doesn't indexOf
, you need to do this yourself:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this && this[from] === elt)
return from;
}
return -1;
};
}
+3
a source to share
var array = ['a', 'b', 'c'];
// The following line returns the zero-based index of 'c'
array.indexOf('c'); // 2
// If the element is not found in the array, -1 is returned:
array.indexOf('z'); // -1
Sorry, Array#indexOf
not supported in Internet Explorer. See SLakss's answer for a working recession!
0
a source to share
Consider Objx for working with arrays http://code.google.com/p/objx/wiki/Plugins
0
a source to share