在开发应用程序时,数组方法多用于获取特定的值列表,并获取单个或多个匹配项。在列出这两种方法的区别之前,我们先来一一了解这几种方法。JavaScriptfind()方法ES6find()方法返回第一个通过测试函数的元素的值。如果没有值满足测试函数,则返回undefined。语法以下语法中使用的箭头函数。find((element)=>{/*...*/})find((element,index)=>{/*...*/})find((element,index,array)=>{/*...*/})我们有一个用户对象列表,其中包含nameage和id属性,如下所示:letusers=[{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}假设没有找到匹配意味着它返回undefinedconsole.log(users.find(user=>user.age===25));//console//undefinedJavaScriptfilter()方法filter()方法创建一个新数组,其中包含所有通过测试函数的元素。如果没有元素满足测试函数,则返回一个空数组。语法filter((element)=>{/*...*/})filter((element,index)=>{/*...*/})filter((element,index,array)=>{/*...*/})我们将使用与过滤器示例相同的用户数组和测试函数。下面的代码使用filter()方法找到第一个年龄大于23岁的用户ageis22//[{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}]假设没有找到匹配意味着它返回一个空arrayconsole.log(users.filter(user=>user.age===25));//console//[]find()和filter()的区别和高阶函数一样:这些两个函数是高阶函数。区别1.通过测试函数find()返回第一个元素。filter()返回一个包含所有通过测试函数的元素的新数组。2.如果没有值满足测试函数find()返回undefined;filter()返回一个空数组;
