学习记录:ES6 数组扩展 - find, findIndex 和 includes
Array.prototype.find
- 作用: 找出第一个符合查找条件的元素
- 参数:一个回调函数 (item, index, array)=> { return … }
- 返回值:符合条件的第一个元素,或者是 undefined
const list = [
{
label: 'red',
value: 1
},
{
label: 'blue',
value: 2
},
{
label: 'yellow',
value: 3
},
{
label: 'green',
value: 2
}
]
const findItem = function (list, value) {
return list.find((item, index, array) => {
return Object.is(item.value, value)
})
}
const findItemEntrance = function (value) {
return findItem(list, value)
}
findItemEntrance(2) // {label: 'blue', value: 2}
findItemEntrance(4) // undefined
ES5中,数组遍历查找的方法:Array.prototype.filter
var num_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var newNum = num_1.filter(filterOne);
function filterOne(x) {
return x % 2 === 0;
}
// newNum 为 [2, 4, 6, 8, 10]
Array.prototype.find 和 Array.prototype.filter 的区别
- 返回值:Array.prototype.find 符合条件的第一个元素,或者是 undefined,Array.prototype.filter 返回的就是一个数组
- 应用场景不一样,只想找某一个元素,Array.prototype.find 就可以决解,若是找一类就需要生产新数组的迭代器 Array.prototype.filter
Array.prototype.findIndex
作用: 找出第一个符合查找条件的元素的索引
参数:一个回调函数 (item, index, array)=> { return … }
返回值:符合条件的第一个元素的索引,否则返回 -1
let list = [1, 3, 6, 8]
let index = list.findIndex((item, index, array) => {
return item >= 5
})
// index 为 2
let index = list.findIndex((item, index, array) => {
return item >= 10
})
// index 为 -1
在 ES5 中有两个方法也是有来找出元素的索引:Array.prototype.indexOf 和 Array.prototype.lastIndexOf这两个方法已经很熟悉,来对比一下和 finindex 的区别:
#### 区别
- 相同点:Array.prototype.indexOf 和Array.prototype. findIndex 都是获取与条件匹配的第一个元素,没有找到则返回 -1
- 不同点:
- 参数,Array.prototype.findIndex 是一个回调函数,Array.prototype.indexOf 有两个参数,第一个是需要查找的元素,第二个参数从哪个位置开始查找
- 对于 NaN 的判断:
- index 内部是用 === 取判断是否与条件匹配, 对于 NaN 会误判
- findIndex 可自定义匹配条件,和 Objext.is() 一起使用可以成功判断是否为 NaN
Array.prototype.includes
- 作用:判读一个元素是否在数组中
- 返回值:Boolean
这个方法也是可以判断 NaN 是否存在 数组中,只能判断有没有,但是不能判断具体的位置。
let list = [1, 2, NaN, 4, 5, 6, NaN]
list.includes(NaN) // true
字符串也是有这个方法,作用类似。