持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第9天,点击查看活动详情
JavaScript开发人员经常被问到的一个常见面试问题是解释find()和filter()方法之间的区别。
在今天的本教程中,我将指导您了解这些方法是什么,以及何时应该使用它们。
What is the filter()
method?
此方法返回满足回调函数中指定的条件的数组中的所有元素。
让我们举个例子看看它实际上是如何工作的:
const x = [1, 2, 3, 4, 5];
const y = x.filter(el => el*2 === 2);
console.log("y is: ", y); // y is: [1]
filter()的示例
如果您查看上述示例的输出,y的值是满足条件的1个元素数组。这是因为filter()方法迭代数组的所有元素,然后返回满足指定条件的过滤数组。
find()
方法是什么?
此方法返回数组中满足回调函数中指定条件的第一个元素。
让我们举个例子看看它实际上是如何工作的:
const x = [1, 2, 3, 4, 5];
const y = x.find(el => el*2 === 2);
console.log("y is: ", y); // y is: 1
find()的例
现在,如果您看到上述示例的输出,y的值是1。 这是因为find()方法搜索数组中满足指定条件的第一个元素。
上述示例的主要区别是:
filter()
返回一个包含满足条件的元素的数组,但find()
返回满足条件的元素本身。- 在
filter()
,尽管正在搜索的元素在开头存在,但整个数组还是被迭代。但是infindfind()
,一旦找到满足条件的元素,它就会被返回。
find()
和filter()
当您有一个预计返回1个以上元素的用例,并且您想对所有元素执行操作时,您可以使用filter() 方法。但是,如果您期望从数组中只返回单个元素,那么您可以使用find() 并避免额外的迭代。
让我们看看这两个用例的例子:
1. filter() 用例示例
const x = [1, 2, 3, 4, 5];
const y = x.filter(el => el%2 === 0);
console.log("y is: ", y); // y is: [2, 4]
filter()用例示例
在上面的示例中,filter()
更有意义,因为你希望迭代数组的所有元素,以找到可被2整除的元素。
2. find() 用例示例
const emp = [
{
name: "Ram",
empID: 101
},
{
name: "Sham",
empID: 102
},
{
name: "Mohan",
empID: 103
}
];
const res = emp.find(el => el.empID === 102);
console.log("res is: ", res); // res is: {name: 'Sham', empID: 102}
find() 用例示例
在上面的示例中,find()
更有意义,因为只有1名员工有102
作为empID
,因此,find()
有助于避免迭代数组中的第三个对象。
结论
感谢你的阅读!