您的位置 首页 php

JavaScript 中 find() 和 filter() 方法的区别

JavaScript 在 ES6 上有很多数组方法,每种方法都有独特的用途和好处。

在开发应用程序时,大多使用数组方法来获取特定的值列表并获取单个或多个匹配项。

在列出这两种方法的区别之前,我们先来一一了解这些方法。

JavaScript find() 方法

ES6 find() 方法返回通过测试函数的第一个元素的值。如果没有值满足测试函数,则返回 undefined。

语法

以下语法中使用的箭头函数。

 find((element) => { /* ... */ } )
find((element, index) => { /* ... */ } )
find((element, index, array) => { /* ... */ } )
  

我们有一个包含名称 age 和 id 属性的用户对象列表,如下所示:

 let users = [{
    id:1,
    name: 'John',
    age: 22
}, {
    id:2,
    name: 'Tom',
    age: 22
}, {
    id:3,
    name: 'Balaji',
    age: 24
}];
  

以下代码使用 find() 方法查找年龄大于 23 的第一个用户。

 console.log(users.find(user => user.age > 23));
//console
//{ id: 3, name: 'Balaji', age:24}
  

现在我们要找到第一个年龄为 22 的用户

 console.log(users.find(user => user.age === 22));
//console
//{ id: 1, name: 'John', age:22}
  

假设没有找到匹配意味着它返回 undefined

 console.log(users.find(user => user.age === 25));
//console
//undefined
  

JavaScript filter() 方法

filter() 方法创建一个包含所有通过测试函数的元素的新数组。如果没有元素满足测试函数,则返回一个空数组。

语法

 filter((element) => { /* ... */ } )
filter((element, index) => { /* ... */ } )
filter((element, index, array) => { /* ... */ } )
  

我们将使用相同的用户数组和测试函数作为过滤器示例。

以下代码使用 filter() 方法查找年龄大于 23 的第一个用户。

 console.log(users.filter(user => user.age > 23));
//console
现在我们要过滤年龄为 22 岁的用户//[{ id: 3, name: 'Balaji', age:24}]
  

现在我们要过滤年龄为 22 岁的用户

 console.log(users.filter(user => user.age === 22));
//console
//[{ id: 1, name: 'John', age:22},{ id: 2, name: 'Tom', age:22}]
  

假设没有找到匹配意味着它返回一个空数组

 console.log(users.filter(user => user.age === 25));
//console
//[]
  

find() 和 filter() 的区别与共点

共点

高阶函数:这两个函数都是高阶函数。

区别

1、通过一个测试功能

find() 返回第一个元素。

filter() 返回一个包含所有通过测试函数的元素的新数组。

2、如果没有值满足测试函数

find() 返回未定义;

filter() 返回一个空数组;

– End –

文章来源:智云一二三科技

文章标题:JavaScript 中 find() 和 filter() 方法的区别

文章地址:https://www.zhihuclub.com/79319.shtml

关于作者: 智云科技

热门文章

网站地图