[乐意黎原创] Array.prototype.find() 与 Array.prototype.findIndex() 使用详解
Array.prototype.find()
find()
方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
。
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
语法
arr.find(callback[, thisArg])
参数
callback
在数组每一项上执行的函数,接收 3 个参数:
element
当前遍历到的元素。
index
可选 当前遍历到的索引。
array
可选 数组本身。
thisArg
可选 执行回调时用作this
的对象。
返回值
数组中第一个满足所提供测试函数的元素的值,否则返回 undefined
。
find
方法不会改变数组。
//用对象的属性查找数组里的对象
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
Array.prototype.findIndex()
findIndex()
方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3
语法
arr.findIndex(callback[, thisArg])
参数
callback
针对数组中的每个元素, 都会执行该回调函数, 执行时会自动传入下面三个参数:
element
当前元素。
index
当前元素的索引。
array
调用findIndex
的数组。
thisArg
可选。执行callback
时作为this
对象的值.
返回值
数组中通过提供测试函数的第一个元素的**索引**。否则,返回-1
//查找数组中首个质数元素的索引
//以下示例查找数组中素数的元素的索引(如果不存在素数,则返回-1)。
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
最后, 使用测试:
//aerchi, test example
var list =[
{"number":0,"name":"弯腰树陈酒","type":9},
{"number":0,"name":"泸西烧洋芋","type":0},
{"number":0,"name":"弥勒红酒","type":1},
{"number":2,"name":"石屏豆腐","type":2},
{"number":6,"name":"宣威火腿","type":4},
{"number":0,"name":"富源火锅","type":3}
];
var temp_wanyaoshu = {number: 0, name: "弯腰树陈酒", type: 9},
/***findIndex****/
list.findIndex((item, index)=>{
return item.name == temp_wanyaoshu.name && (item.type == temp_wanyaoshu.type);
})
//0
list.findIndex((item, index)=>{
return (item.name == "宣威火腿" && (item.type == 4) );
})
//4
list.findIndex((item, index)=>{
return (item.name == "宣威火腿" && (item.type == 41) );
})
//-1
/***find****/
list.find((item, index)=>{
return item.name == temp_wanyaoshu.name && (item.type == temp_wanyaoshu.type);
})
//{number: 0, name: "弯腰树陈酒", type: 9}
list.find((item, index)=>{
return (item.name == "宣威火腿" && (item.type == 4) );
})
//{number: 6, name: "宣威火腿", type: 4}
list.find((item, index)=>{
return (item.name == "宣威火腿" && (item.type == 41) );
})
//undefined
let item_wanyaoshu_index = -1;
// 不包含, 返回 index or -1
item_wanyaoshu_index = list.findIndex((item, index)=>{
return item.name == temp_wanyaoshu.name && (item.type == temp_wanyaoshu.type);
});
if( item_wanyaoshu_index==-1){
list.unshift(temp_wanyaoshu);
}
乐意黎
2020-09-11
还没有评论,来说两句吧...