views:

122

answers:

3
var fruits = [ 'apple', 'banana', 'orange' ];

how do I find what index of the value "banana" is? (which, of course, is "1").

thanks

A: 

Well, this might help you: How to Find the Index/Position of an element in an array

mr.bio
+10  A: 

As shown here: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/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;
  };
}

Usage:

var fruits = [ 'apple', 'banana', 'orange' ];
var index = fruits.indexOf('banana');

Will return '1'

Dustin Laine
>>> is new to me. What does it do? Google is useless for it!
spender
This should be included at the top of your scripts and basically extends JavaScript to include the method. I am updating my answer with the usage.
Dustin Laine
@spender, that is the *unsigned right shift* bitwise operator, in this context, they use it just to ensure that the `length` value is a 32-bit unsigned integer (all bitwise operators internally work with 32-bit ints)...
CMS
+4  A: 

There is no built-in property to return the index of a particular item. If you need a function then you can use the prototype function as defined by durilai. But if you just need to find the index you can use this simple code block to return the value:

for (var i=0; i<fruits.length; i++)
{
  if (fruits[i] == "banana")
  {
    alert(i);
  }
}
Peter Jacoby