var fruits = [ 'apple', 'banana', 'orange' ];
How to find the banana index? (which, of course, is equal to "1").
thanks
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; }; }
Using:
var fruits = [ 'apple', 'banana', 'orange' ]; var index = fruits.indexOf('banana');
Will return '1'
There is no built-in property to return the index of a specific item. If you need a function, you can use the prototype function defined by durilai. But if you just need to find the index, you can use this simple block of code to return the value:
for (var i=0; i<fruits.length; i++) { if (fruits[i] == "banana") { alert(i); } }