javascript - Map、findIndex 和 filter 组合

标签 javascript

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

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

filter 也会为每个 notes 执行一次,或者在所有 notesmap 循环后才执行一次?

最佳答案

.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?

来自docs :

The filter() method creates a new array with all elements that pass the test implemented by the provided function

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

全部falsy JavaScript 中的值:

  • null
  • 错误
  • 0
  • ''/""
  • 未定义
  • NaN

关于javascript - Map、findIndex 和 filter 组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50205608/

相关文章:

javascript - 如何验证外部 javascript 文件中的选择下拉列表值不为空?

javascript - 使用javascript更改另一个范围内的变量值

javascript - 无法触发链接上的点击事件

javascript - 如何在 JavaScript 中过滤和映射对象数组?

javascript - 通过 D3 中的嵌套为 JSON 创建键值对

javascript - 输入框文本值技巧

javascript - 如何将 mouseover/mouseout 监听器添加到 ol.Map?

javascript - 遍历数组并将项目与 html 元素匹配

javascript - ReactJs 中定义组件的两种方式之间的区别

javascript - 更改 mootools 表单验证器的默认错误消息