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

前端 未结 2 1990
礼貌的吻别
礼貌的吻别 2020-12-11 05:39
var fruits = [ \'apple\', \'banana\', \'orange\' ];

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

than

2条回答
  •  孤城傲影
    2020-12-11 06:15

    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'

提交回复
热议问题