omg
omg

Reputation: 139862

Javascript array operation

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

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

Upvotes: 0

Views: 1025

Answers (3)

NawaMan
NawaMan

Reputation: 25687

arr.indexOf('hello');

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

:-D

Upvotes: 0

Steve Harrison
Steve Harrison

Reputation: 125500

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;
  };
}

Upvotes: 3

Greg
Greg

Reputation: 321598

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

Upvotes: 2

Related Questions