×

JavaScript:学下find()和 filter()

作者:abc1232022.01.20来源:Web前端之家浏览:2655评论:0
关键词:js

JavaScript:find()和 filter()。

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() 返回一个空数组;

let arr = [
  {
    name: 'Rick',
    age: 60
  },

  {
    name: 'Rick',
    age: 70
  },

  {
    name: 'Morty',
    age: 14
  }

]

let findResult = arr.find(i => i.name === 'Rick')
let filterResult = arr.filter(i => i.name === 'Rick')

console.log(arr); 
/*  输出结果
  [
    {
      name: "Rick",
      age: 60
    },

    {
      name: "Rick",
      age: 70
    },

    {
      name: "Morty",
      age: 14
    }
  ]

*/

console.log(findResult);   // {name: "Rick", age: 60}
console.log(filterResult);  // [{name: "Rick", age: 60}, {name: "Rick", age: 70}]

根据以上代码输出结果,可以发现 find 和 filter 都不改变原数组。

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js20220120a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: