简体   繁体   English

如何获取数组中项的索引?

[英]How do I get the index of an item in an array?

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

how do I find what index of the value "banana" is? 如何找到值“banana”的索引是什么? (which, of course, is "1"). (当然,这是“1”)。

thanks 谢谢

As shown here: 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;
  };
}

Usage: 用法:

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

Will return '1' 将返回'1'

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. 如果您需要一个函数,那么您可以使用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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM