JavaScript Array.find
方法是一个方便的方式来 find
并返回一个数组中的元素的第一个出现,在一个定义的测试函数下。
如何使用 Array.find
find()
的函数和语法非常类似于 Array.filter 方法,但它只返回一个元素。
因此,如果您只需要一个值,请使用 find()
! 当您需要找到/返回多个值时,请选择 filter()
。
如何使用 Array.find
使用find()
非常容易! 这个方法所需的唯一参数是测试函数,它可以是必要的简单或复杂。
1array.find(testingFunction); // that's it!
简单的例子:
以下是一個簡單的例子,有幾個字符串:
1const trees = [
2 "birch",
3 "maple",
4 "oak",
5 "poplar"
6];
7
8const result = trees.find(tree => tree.startsWith("m"));
9
10// "maple"
非短语、非ES6形式:
1const result = trees.find(function(tree) {
2 return tree.startsWith("m");
3});
4
5// "maple"
使用物件:
我们也可以使用find()
来轻松搜索对象的数组!
1const trees = [
2 { name: "birch", count: 4 },
3 { name: "maple", count: 5 },
4 { name: "oak", count: 2 }
5];
6
7const result = trees.find(tree => tree.name === "oak");
8
9// { name: "oak", count, 2 }
使用相同的例子,注意如果我们使用find()
,当测试有多个结果时,我们只能获得第一个值:
1const result = trees.find(tree => tree.count > 2);
2
3// { name: "birch", count: 4 }
這是一個例子,你應該使用「filter()」而不是「filter()」。
提示:分离测试功能
有时你会想在多个地方重复使用相同的find()
测试函数,在这种情况下,创建一个单独的测试函数非常有用。
让我们演示这个技术,扩展到我们之前的例子:
1const deciduous = [
2 { name: "birch", count: 4 },
3 { name: "maple", count: 5 },
4 { name: "oak", count: 2 }
5];
6
7const evergreens = [
8 { name: "cedar", count: 2 },
9 { name: "fir", count: 6 },
10 { name: "pine", count: 3 }
11];
12
13// our testing function
14const hasFiveOrMore = el => el.count >= 5;
15
16const decResult = deciduous.find(hasFiveOrMore);
17// { name: "maple", count: 5 }
18
19const evgResult = evergreens.find(hasFiveOrMore);
20// { name: "fir", count: 6 }
简单,但强大!
使用指数参数
像filter()
一样,我们可以使用一个可选的索引
参数,这里是最后一个例子,使用它作为我们的测试功能的一部分:
1const evergreens = [
2 { name: "cedar", count: 2 },
3 { name: "fir", count: 6 },
4 { name: "pine", count: 3 }
5];
6
7// suppose we need to skip the first element
8const result = evergreens.find((tree, i) => {
9 if (tree.count > 1 && i !== 0) return true;
10});
11
12// { name: "fir", count: 6 }
索引
可能不是你经常需要的东西 - 但有时有它是很棒的。
结论
「Array.find」是一个简单但非常有用的方法来搜索JavaScript数组. 它是数组上可用的几个有用的方法之一,如需更完整的指南,请参阅 How To Use Array Methods in JavaScript: Iteration Methods。
请记住:当你想要一个单个元素返回时,只使用查找
,如果没有找到任何元素,它会返回未定义
!否则,当你需要返回多个元素时,请使用 filter
方法。