indexOf
indexOf 方法返回指定的元素在数组中第一次出现的索引,如果没找到则返回 -1
语法:array.indexOf(ele, index)
ele:要查找的指定的元素
index:指定要开始查找的位置,默认为0。如果为负值,则表示从倒数第几个开始查找,此时查找的方向不变,还是从前往后查找。
返回值:首个被找到的元素在数组中的索引,没找到返回 -1
const arr = ['a', 'b', 'c', 'b', 'c', 'd', 'e']
arr.indexOf('b') // 1
arr.indexOf('b', 2) // 3
arr.indexOf('c', -2) // -1
arr.indexOf('c', -3) // 4
arr.indexOf('A') // -1
lastIndexOf
lastIndexOf 方法返回指定元素在数组中最后一次出现的位置,如果没有则返回 -1。该方法从数组的后面向前查找。
语法:array.lastIndexOf(ele, index)
ele:要查找的元素
index:指定要查找的元素的位置,从此位置开始逆向查找。默认为数组的长度减去1(array.length - 1)。如果为负值,则表示从倒数第几个开始向前查找,此时查找的方向不变还是从后向前查找。
返回值:返回元素最后一次在数组出现的索引,没找到返回 -1
const arr = ['a', 'b', 'c', 'b', 'c', 'd', 'e']
arr.lastIndexOf('c') // 4
arr.lastIndexOf('c', -4) // 2
arr.lastIndexOf('c', 2) // 2
arr.lastIndexOf('c', 1) // -1
arr.lastIndexOf('A') // -1
ndexOf和lastIndexOf 方法查找特定的元素的时候都是使用 严格相等(===)做比较