filter 筛选函数

252 阅读1分钟

filter()方法创建一个新数组,其包含通过所提供函数实现测试的所有元素。

filter尝试一下

  • 是把长度大于6的单词过滤出来,组成一个新的数组;
const words = ['spray','limit','elite','exuberant', 'destruction', 'present']
const result = words.filter(word=>word.length > 6)
console.log(result)
结果打印出:
> Array ["exuberant", "destruction", "present"]

map尝试一下

  • 只是把单词的长度,打印出来。
const words = ['spray','limit','elite','exuberant', 'destruction', 'present']
const result = words.map(word=>word.length )
console.log(result)
结果打印出:
> Array [5, 5, 5, 9, 11, 7]

map和filter的区别

  • map是对数组做了一次统一的映射,filter是做了一次过滤,更通俗点就是,map函数之后,数组元素个数不变,但是按照一定的条件转换,数组元素发生了变化;
  • filter函数之后,数组元素个数可能发生了变化,但是数组元素不会变化。

应用:筛选出来相同元素的

  • 背景:当输入相同的手机号或其他时,要能筛选出来;
if (form.contacts.filter(item=>item.phoneNum === value).length > 1){
  callback(new Error('相同手机号'))
}else{
  callback()
}
  • 上面是自定义里面的一个应用
  • 自定义在elementui里面有案例,可以模仿使用;
  • 详情可以参考《自定义filter提示重复》,这篇文章。