ES6 新增数组方法 find()和 findIndex()

  • 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'] = '游泳';
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大杯美式不加糖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值