本网站可以出售:只需60000元直接拥有。QQ:939804642
您当前的位置:首页 > 网站建设 > javascript
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax | jQuery | 小程序 |

JavaScript中find()和

51自学网 2022-02-21 13:34:57
  javascript

前言

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

直接上代码

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 都不改变原数组

总结

到此这篇关于JavaScript中find()和filter()方法的区别小结的文章就介绍到这了,更多相关js
下载地址:
JavaScript字符串转换数字的方法
JavaScript定时器类型总结

51自学网自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1