indexOf
与 findIndex
都是查找数组中知足条件的第一个元素的索引前端
indexOf
Array.prototype.indexOf():git
indexOf()
方法返回在数组中能够找到一个给定元素的第一个索引,若是不存在,则返回-1。github来自:MDN面试
例如:算法
const sisters = ['a', 'b', 'c', 'd', 'e']; console.log(sisters.indexOf('b')); // 1
请注意: indexOf()
使用严格等号(与 ===
或 triple-equals 使用的方法相同)来比较 searchElement
和数组中的元素数组
因此,indexOf
更多的是用于查找基本类型,若是是对象类型,则是判断是不是同一个对象的引用函数
let sisters = [{a: 1}, {b: 2}]; console.log(sisters.indexOf({b: 2})); // -1 const an = {b: 2} sisters = [{a: 1}, an]; console.log(sisters.indexOf(an)); // 1
findIndex
Array.prototype.findIndex():测试
findIndex()
方法返回数组中知足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。this来自:MDNurl
const sisters = [10, 9, 12, 15, 16]; const isLargeNumber = (element) => element > 13; console.log(sisters.findIndex(isLargeNumber)); // 3
findIndex
指望回调函数做为第一个参数。若是你须要非基本类型数组(例如对象)的索引,或者你的查找条件比一个值更复杂,能够使用这个方法。
indexOf 与 findIndex 区别(总结)
-
indexOf
:查找值做为第一个参数,采用===
比较,更多的是用于查找基本类型,若是是对象类型,则是判断是不是同一个对象的引用 -
findIndex
:比较函数做为第一个参数,多用于非基本类型(例如对象)的数组索引查找,或查找条件很复杂
源码实现(加深)
indexOf
:
if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (len === 0) { return -1; } var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } if (n >= len) { return -1; } k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (k in O && O[k] === searchElement) { // === 匹配 return k; } k++; } return -1; }; }
findIndex
:
if (!Array.prototype.findIndex) { Object.defineProperty(Array.prototype, 'findIndex', { value: function(predicate) { if (this == null) { throw new TypeError('"this" is null or not defined'); } var o = Object(this); var len = o.length >>> 0; if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var thisArg = arguments[1]; var k = 0; while (k < len) { var kValue = o[k]; if (predicate.call(thisArg, kValue, k, o)) { // 比较函数判断 return k; } k++; } return -1; } }); }