数组find(),findIndex(),indexOf(),lastIndexOf(),include()
作者:互联网
var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
1.find() 返回数组中第一个满足条件的数据
// var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var newNum1 = num.find((item, index) => {
return item > 40;
})
console.log("newNum1 = " + newNum1);//50
2.findIndex() 返回数组中第一个满足条件的索引(从0开始), 不满足返回-1
// var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var newNum2 = num.findIndex((item, index) => {
return item > 40;
})
console.log("newNum2 = " + newNum2);//4
3.indexOf() 返回数组中第一个满足条件的索引(从0开始), 不满足返回-1
语法:arr.indexOf(searchElement[, fromIndex = 0])
// var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var newNum3 = num.indexOf(40);
var newNum4 = num.indexOf(40, 10);//从索引10的位置开始向后查找
console.log("newNum3 = " + newNum3);//3
console.log("newNum4 = " + newNum4);//-1
4.lastIndexOf() 返回数组中最后一个满足条件的索引(从0开始), 不满足返回-1
语法:arr.lastIndexOf(searchElement[, fromIndex = arr.length - 1])
// var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var newNum5 = num.lastIndexOf(40);
var newNum6 = num.lastIndexOf(40, 1);//从索引1的位置开始向前查找
console.log("newNum5 = " + newNum5);//3
console.log("newNum6 = " + newNum6);//-1
5.include() 判断数组宏是否包含某值,返回 true 或 false
语法:arr.includes(searchElement[, fromIndex])
// var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var newNum7 = num.includes(40);
var newNum8 = num.includes(40, 5);//从索引5的位置开始向后查找
console.log("newNum7 = " + newNum7);//true
console.log("newNum8 = " + newNum8);//false
代码合并
var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
// 1.find() 返回数组中第一个满足条件的数据
// var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var newNum1 = num.find((item, index) => {
return item > 40;
})
console.log("newNum1 = " + newNum1);//50
// 2.findIndex() 返回数组中第一个满足条件的索引(从0开始), 不满足返回-1
// var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var newNum2 = num.findIndex((item, index) => {
return item > 40;
})
console.log("newNum2 = " + newNum2);//4
// 3.indexOf() 返回数组中第一个满足条件的索引(从0开始), 不满足返回-1
// 语法:arr.indexOf(searchElement[, fromIndex = 0])
// var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var newNum3 = num.indexOf(40);
var newNum4 = num.indexOf(40, 10);//从索引10的位置开始向后查找
console.log("newNum3 = " + newNum3);//3
console.log("newNum4 = " + newNum4);//-1
// 4.lastIndexOf() 返回数组中最后一个满足条件的索引(从0开始), 不满足返回-1
// 语法:arr.lastIndexOf(searchElement[, fromIndex = arr.length - 1])
// var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var newNum5 = num.lastIndexOf(40);
var newNum6 = num.lastIndexOf(40, 1);//从索引1的位置开始向前查找
console.log("newNum5 = " + newNum5);//3
console.log("newNum6 = " + newNum6);//-1
// 5.include() 判断数组宏是否包含某值,返回 true 或 false
// 语法:arr.includes(searchElement[, fromIndex])
// var num = [10, 20, 30, 40, 50, 60, 70, 80, 90];
var newNum7 = num.includes(40);
var newNum8 = num.includes(40, 5);//从索引5的位置开始向后查找
console.log("newNum7 = " + newNum7);//true
console.log("newNum8 = " + newNum8);//false
标签:10,findIndex,lastIndexOf,log,indexOf,40,num,var,console 来源: https://blog.csdn.net/qq_42801351/article/details/122595162