Array.prototype.indexOf()和Array.prototype.lastIndexOf()
Array.prototype.indexOf()
indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
searchElement
要查找的元素
fromIndex
开始查找的位置。如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回-1。如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消,即-1表示从最后一个元素开始查找,-2表示从倒数第二个元素开始查找 ,以此类推。 注意:如果参数中提供的索引值是一个负值,并不改变其查找顺序,查找顺序仍然是从前向后查询数组。如果抵消后的索引值仍小于0,则整个数组都将会被查询。其默认值为0。
返回首个被找到的元素在数组中的索引位置; 若没有找到则返回 -1。
indexOf使用严格等于来判断。
var array = [2, 5, 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']; // New veggies collection is : potato,tomato,chillies,green-papper,spinach updateVegetablesCollection(veggies, 'spinach'); // spinach already exists in the veggies collection. updateVegetablesCollection(veggies, 'spinach');
polyfill
indexOf 在ECMA-262 标准 的第5版中被加入,但并非所有的浏览器都支持该方法。你可以在编写scripts时,在其开头使用以下代码,它能够允许你在没有本地支持的情况下使用indexOf方法。该算法符合ECMA-262第5版其中一项规定, 即假定 TypeError和 Math.abs 呈现它们原有的价值。
// 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) {//数组为undefined抛错误 throw new TypeError('"this" is null or not defined'); } var O = Object(this);//将this转换成object // 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;//右移0位取整 // 4. If len is 0, return -1. if (len === 0) {//数组长度为0,返回-1 return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0;//处理起始索引,加号转换成Number类型 if (Math.abs(n) === Infinity) {//如果是无限,就赋值为0 n = 0; } // 6. If n >= len, return -1. if (n >= len) {//起始索引>=数组长度,返回-1 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; }; }
Array.prototype.lastIndexOf()
lastIndexOf() 方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。
searchElement
被查找的元素。
fromIndex
从此位置开始逆向查找。默认为数组的长度减 1,即整个数组都被查找。如果该值大于或等于数组的长度,则整个数组会被查找。如果为负值,将其视为从数组末尾向前的偏移。即使该值为负,数组仍然会被从后向前查找。如果该值为负时,其绝对值大于数组长度,则方法返回 -1,即数组不会被查找。
返回查找到元素的最后一个索引,找不到返回-1。
lastIndexOf使用严格相等。
var array = [2, 5, 9, 2]; var index = array.lastIndexOf(2); // index is 3 index = array.lastIndexOf(7); // index is -1 index = array.lastIndexOf(2, 3); // index is 3 index = array.lastIndexOf(2, 2); // index is 0 index = array.lastIndexOf(2, -2); // index is 0 index = array.lastIndexOf(2, -1); // index is 3 index = array.lastIndexOf(2, -100); //index is -1
查找所有元素的下标
var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.lastIndexOf(element); while (idx != -1) { indices.push(idx); idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1); } console.log(indices); // [4, 2, 0];
注意,我们要单独处理idx==0时的情况,因为如果是第一个元素,忽略了fromIndex参数则第一个元素总会被查找。这不同于indexOf方法
polyfill
lastIndexOf 在 ECMA-262 标准第 5 版被添加。因此它在不兼容该标准的浏览器中可能不被支持。你可以把下面代码添加到脚本中来使那些没有实现该方法的实现环境支持该方法。该算法是被 ECMA-262 第 5 版指定的。假定 Object、TypeError、Number、Math.floor、Math.abs,以及 Math.min 拥有其初始值。
if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) { 'use strict'; if (this === void 0 || this === null) {//void 0返回undefined,防止undefined被重写 throw new TypeError();//如果this是undefined,抛错误 } var n, k, t = Object(this), len = t.length >>> 0; if (len === 0) {//数组长度为0返回-1 return -1; } n = len - 1;//从数组最后一个元素索引开始查找 if (arguments.length > 1) {//传了第二个参数fromIndex n = Number(arguments[1]);//转换成数字 if (n != n) {//如果是NaN n = 0; } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {//n不等于0,Infinity,-Infinity n = (n > 0 || -1) * Math.floor(Math.abs(n));//对n取整,没有处理负数情况 } } for (k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) {//处理fromIndex是负数情况 if (k in t && t[k] === searchElement) {//找到目标元素然后返回对应索引 return k; } } return -1; }; }