程序猿头头:数组应用(indexOf,includes,find,findindex)

数组应用(indexOf,includes,find,findindex)

1.indexOf 寻找下标
从左到右搜索第一个===的下标。

[1,2,3].indexOf(1);	// 0
[1,2,3].indexOf('1');	// -1,因为不全等,找不到就返回-1
[1,2,3,1,5,6].indexOf(1, 2);	// 3,第二个参数是从x下标开始搜索

lastIndexOf
从右往左搜索第一个===的下标。

[1,2,3,1,5,7].lastIndexOf(1);	// 3
[1,2,3,1,5,7,1,5].lastIndexOf(1, 100);	// 6 第二个参数是从x下标开始搜索
[1,2,3,1,5,7,1,5].lastIndexOf(1, 5);	// 3

includes
判断数组内是否有===的项。

[1,2,3,4,5,6].includes(1);	// true
[1,2,3,4,5,6].includes('1');	// false,因为不全等
[1,2,3,4,5,6].includes(8);	// false

find
根据条件查找数组内的单个项,根据条件查找项,只要返回true那就证明找到了,如果为false的话,那就继续遍历查找。

[1,2,3].find(c=> c === 1);	// 1
[1,2,3].find(c=> c == '1');	// 1
[1,2,3].find(c=> c === 5);	// undefined
[1,2,3].find(c=> c > 1);	// 2

const people = [{
    name: "Matt",
    age: 27
},
{
    name: "Nicholas",
    age: 29
}];
//三个参数分别是:当前遍历的项、当前下标、原始数组。
let p = people.find((element, index, array) => {
    console.log(element, index, array);
    return element.age > 28;
});
console.log(p);		// {name: "Nicholas", age: 29}

findIndex
根据条件查找数组内匹配项的下标。

[{ age: 20 }, { age: 18 }, { age: 10 }].findIndex(function (item) {
	return item.age === 10
});	//2
[1,2,3].findIndex(c=> c === 5);	// -1
[1,2,3].findIndex(c=> c > 1);	// 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值