Map、findIndex和filter的组合使用

3

我遇到了下面这个函数,不太确定它在做什么。特别是 .filter(note => note) 的目的是什么?

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

同时,filter会被执行每一个notes还是只在所有notesmap循环后执行一次?
3个回答

3

.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中所有falsy值:

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

2
它检查note是否为真值 - 如果不是真值,则该元素不会被包含在计算的laneNotes中。

例如:

console.log(
  [0, 1, 2].filter(num => num)
);

所涉及的代码简而言之如下所示:

laneNotes: props.lane.notes.map((id) => {
  const foundIndex = state.notes.findIndex(note => note.id === id);
  return state.notes[foundIndex];
}).filter(note => note);

它使用findIndex来查找匹配的note,但如果没有找到匹配的note,则foundIndex将为-1,因此state.notes[foundIndex]将是未定义的。 .filter函数的目的是将这些undefined从结果中排除。

@@maxflow可能不是真实的,因为findIndex可能返回-1,其索引在数组中不存在 - 请参见编辑。 - CertainPerformance

1

简单来说- .filter(n => n) 会移除空值(非真值),而且它会遍历映射数组(由.map返回)中的每个项。

你一定要看文档:mozilla.org -> filter :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接