find()
找到满足条件的一个立即返回findIndex()
找到满足条件的一个,立即返回其索引
基本用法
find()
const arr = [1, 5, 10, 15];
console.log(arr.find((value, index, arr) => {
console.log(value, index, arr);
// 输出:
// 1 0 [1, 5, 10, 15]
// 5 1 [1, 5, 10, 15]
// 10 2 [1, 5, 10, 15]
// 15 3 [1, 5, 10, 15]
return value > 9; // 10 只返回第一个满足条件的值,即10
}));
findIndex()
const arr = [1, 5, 10, 15];
console.log(arr.findIndex((value, index, arr) => {
return value > 9; // 2 只返回第一个满足条件的值,即“10”的下标:“2”
}));
第二个参数
修改this指向
const arr = [1, 5, 10, 15];
console.log(arr.find((value, index, arr) => {
console.log(this); // window
}));
console.log(arr.find(function (value, index, arr) {
console.log(this); // #document 上面不能用箭头函数噢
}, document));
// findIndex 同上
应用
const students = [
{
name: '张三',
sex: '男',
age: 22
},
{
name: '李四',
sex: '女',
age: 20
},
{
name: '王五',
sex: '男',
age: 24
},
];
// 要把第一个女学生挑出来,怎么做呢?
console.log(
students.find(value => value.sex === '女')
); // {name: '李四', sex: '女', age: 20}
// 找到name为“李四”的数据,添加一个hobby属性,属性值为“游泳”
var index = students.findIndex(value => value.name === '李四');
students[index]['hobby'] = '游泳';