首页 > 解决方案 > Map、findIndex 和 filter 组合

问题描述

我在下面遇到了一个函数,但不完全确定它在做什么。具体目的是.filter(note => note)什么?

laneNotes: props.lane.notes.map(id => state.notes[
  state.notes.findIndex(note => note.id === id)
]).filter(note => note)

在所有被循环之后,是否也会filter为每个notes或仅执行一次?notesmap

标签: javascript

解决方案


.filter(note => note)将过滤所有falsy值。它相当于:.filter(Boolean)

Also does filter get executed for each notes 
or only once after all notes are looped over by map?

文档

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

console.log([0, 2, '', false, null, true, undefined].filter(item => item));
console.log([0, 2, '', false, null, true, undefined].filter(Boolean));

javascript 中的所有虚假值:

  • null
  • false
  • 0
  • ''/""
  • undefined
  • NaN

推荐阅读