var arr = ['test','hello'];
is there a javascript native call to get index of some value('hello') in an array?
var arr = ['test','hello'];
is there a javascript native call to get index of some value('hello') in an array?
arr.indexOf("hello");
The indexOf
method isn't supported in all browsers (it was added in JavaScript 1.6), but you can use the following code to make it work in those that don't (code from the MDC page for indexOf
):
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;
};
}
In javascript 1.6+ you can use .indexOf()
:
var index = arr.indexOf('hello');
In earlier versions you would just have to loop through the array yourself.
Interestingly, alert([].indexOf)
in Chrome gives you the implementation:
function indexOf(element, index) {
var length = this.length;
if (index == null) {
index = 0;
} else {
index = (_IsSmi(IS_VAR(index)) ? index : ToInteger(index));
if (index < 0) index = length + index;
if (index < 0) index = 0;
}
for (var i = index; i < length; i++) {
var current = this[i];
if (!(typeof(current) === 'undefined') || i in this) {
if (current === element) return i;
}
}
return -1;
}
Don't ask me what _IsSmi(IS_VAR(index))
does though...