0

var arr = ['test','hello'];

is there a javascript native call to get index of some value('hello') in an array?

3 Answers 3

3
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;
  };
}
Sign up to request clarification or add additional context in comments.

Comments

2

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...

7 Comments

where to see my javascript version?
the best thing to do is just see if it's supported - if (typeof [].indexOf == 'undefined') { you don't have it }
It's suppored,but still don't know javascript version:(
You'd need to check the version of your browser and look it up
Kudos for finding the actual implementation. Definitely worth a +1
|
0
arr.indexOf('hello');

I don't know if it works on IE though (It surely works on Firefox and Webkit).

:-D

1 Comment

I really don't know why do I get vote down .... My answer is not much different from other (surely not wrong). ???

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.