javascript - 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
或仅执行一次?notes
map
解决方案
.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
推荐阅读
- javascript - Javascript:子/子对象应该使用由其父对象实例化的依赖项,还是应该实例化自己的依赖项实例?
- javascript - 使用 sequelize findAll 时,forEach 找不到正确的用户 ID
- php - PHP DateTime 在 WHILE 循环期间写出值
- c - 在 C 中打印二维手机键盘中的每个解锁图案
- python - 构建图形时在 python 中使用下划线变量
- php - 从 python/PHP 打印
- javascript - 路由更改时重新安装组件
- c++ - 使用浮点键实现类似哈希表的数据结构,其中容差内的值被合并在一起
- java - 如何更正此代码以正确加载 ImageIcon
- python - asyncio/aiohttp - 如何进行一系列异步 - 但依赖 - 请求?