views:

136

answers:

3

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

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

+3  A: 
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;
  };
}
Steve Harrison
+2  A: 

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

Greg
where to see my javascript version?
Shore
the best thing to do is just see if it's supported - if (typeof [].indexOf == 'undefined') { you don't have it }
Greg
It's suppored,but still don't know javascript version:(
Shore
You'd need to check the version of your browser and look it up
Greg
Kudos for finding the actual implementation. Definitely worth a +1
Christopher W. Allen-Poole
Not much use posting an implementation that relies on one browser's internal properties (and won't work as user code even on that browser), when somebody's posted an implementation that works cross-browser.
NickFitz
The answer is at the top. The Chrome implementation was just for interest
Greg
A: 
arr.indexOf('hello');

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

:-D

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