非常教程

JavaScript参考手册

排列 | Array

array.indexOf

indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

注意:对于String方法,请参阅String.prototype.indexOf()

var a = [2, 9, 9]; 
a.indexOf(2); // 0 
a.indexOf(7); // -1

if (a.indexOf(7) === -1) {
  // element doesn't exist in array
}

语法

arr.indexOf(searchElement[, fromIndex])

参数

searchElement

要查找的元素fromIndex开始查找的位置。如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回-1。如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消,即-1表示从最后一个元素开始查找,-2表示从倒数第二个元素开始查找 ,以此类推。 注意:如果参数中提供的索引值是一个负值,并不改变其查找顺序,查找顺序仍然是从前向后查询数组。如果抵消后的索引值仍小于0,则整个数组都将会被查询。其默认值为0.

返回值

首个被找到的元素在数组中的索引位置; 若没有找到则返回 -1

描述

indexOf使用strict equality(无论是 ===, 还是 triple-equals操作符都基于同样的方法)进行判断searchElement与数组中包含的元素之间的关系。

示例

使用indexOf()

以下例子使用indexOf()方法确定多个值在数组中的位置。

var array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

找出指定元素出现的所有位置

var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]

判断一个元素是否在数组里,不在则更新数组

function updateVegetablesCollection (veggies, veggie) {
    if (veggies.indexOf(veggie) === -1) {
        veggies.push(veggie);
        console.log('New veggies collection is : ' + veggies);
    } else if (veggies.indexOf(veggie) > -1) {
        console.log(veggie + ' already exists in the veggies collection.');
    }
}

var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];

updateVegetablesCollection(veggies, 'spinach'); 
// New veggies collection is : potato,tomato,chillies,green-pepper,spinach
updateVegetablesCollection(veggies, 'spinach'); 
// spinach already exists in the veggies collection.

Polyfill

indexOf()在ECMA-262 标准 的第5版中被加入,但并非所有的浏览器都支持该方法。你可以在编写scripts时,在其开头使用以下代码,它能够允许你在没有本地支持的情况下使用indexOf()方法。该算法符合ECMA-262第5版其中一项规定, 即假定TypeErrorMath.abs()呈现它们原有的价值。

if (!Array.prototype.indexOf)
  Array.prototype.indexOf = function(searchValue, index) {
    // In non-strict-mode, if the `this` variable is null
    // or undefined, then it is set the the window object.
    // Else, `this` is automaticly converted to an object.
    var len = this.length >>> 0; // convert ot number or 0
    
    index |= 0;              // rounds and NaN-checks
    if (index < 0)             // check if negative start
      index = Math.max(len - index, 0);
    else if (index >= len) // else, check if too big
      return -1;
    
    if (searchValue === undefined)
      // Because searchValue is undefined, keys that
      // don't exist will have the same value as the
      // searchValue, and thus do need to be checked.
      do {
        if (index in this && this[index] === undefined)
          return index;
      } while (++index !== len)
    else
      // Because searchValue is not undefined, there's no
      // need to check if the current key is in the array
      // because if the key isn't in the array, then it's
      // undefined which is not equal to the searchValue.
      do {
        if (this[index] === searchValue)
          return index;
      } while (++index !== len)
    
    // if nothing was found, then simply return -1
    return -1;
  };

但是,如果您对ECMA标准定义的所有小技术更感兴趣,并且不太关注性能或简洁性,那么您可能会发现这种更具描述性的polyfill更有用。

// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {

    var k;

    // 1. Let o be the result of calling ToObject passing
    //    the this value as the argument.
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }

    var o = Object(this);

    // 2. Let lenValue be the result of calling the Get
    //    internal method of o with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = o.length >>> 0;

    // 4. If len is 0, return -1.
    if (len === 0) {
      return -1;
    }

    // 5. If argument fromIndex was passed let n be
    //    ToInteger(fromIndex); else let n be 0.
    var n = fromIndex | 0;

    // 6. If n >= len, return -1.
    if (n >= len) {
      return -1;
    }

    // 7. If n >= 0, then Let k be n.
    // 8. Else, n<0, Let k be len - abs(n).
    //    If k is less than 0, then let k be 0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    // 9. Repeat, while k < len
    while (k < len) {
      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the
      //    HasProperty internal method of o with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      //    i.  Let elementK be the result of calling the Get
      //        internal method of o with the argument ToString(k).
      //   ii.  Let same be the result of applying the
      //        Strict Equality Comparison Algorithm to
      //        searchElement and elementK.
      //  iii.  If same is true, return k.
      if (k in o && o[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}

规范

Specification

Status

Comment

ECMAScript 5.1 (ECMA-262)The definition of 'Array.prototype.indexOf' in that specification.

Standard

Initial definition. Implemented in JavaScript 1.6.

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Array.prototype.indexOf' in that specification.

Standard

ECMAScript Latest Draft (ECMA-262)The definition of 'Array.prototype.indexOf' in that specification.

Living Standard

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

(Yes)

(Yes)

1.5

9

(Yes)

(Yes)

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

(Yes)

(Yes)

1

(Yes)

(Yes)

(Yes)

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络