我如何获得一个项目的数组索引? [英] How do I get the index of an item in an array?
本文介绍了我如何获得一个项目的数组索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var fruits = [ 'apple', 'banana', 'orange' ];
我怎么查找索引值的香蕉是什么? (其中,当然,是1)。
how do I find what index of the value "banana" is? (which, of course, is "1").
感谢
推荐答案
如下所示:<一href=\"https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf\">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;
};
}
用法:
var fruits = [ 'apple', 'banana', 'orange' ];
var index = fruits.indexOf('banana');
将返回1
这篇关于我如何获得一个项目的数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文