reduce使用遇到的问题
# 示例
筛选出状态为is_online的id集合
const authors = [
{
is_star: true,
is_online: false,
id:1
},
{
is_star: true,
is_online: true,
id:2
},
{
is_star: true,
is_online: false,
id:3
},
{
is_star: true,
is_online: true,
id:4
},
{
is_star: true,
is_online: true,
id:5
}
]
# 过滤数组+返回数据
const result = authors.filter(v => v.is_online).map(v=> v.id)
还有一种方式就是reduce
const result = authors.reduce((v,current) => {
if(current.is_online){
return v.push(current.id)
}
return v
}, [])
// []
// 1
// v.push is not function
- 出错了, 哪里错误了呢
- 经过分析是在return的时候犯错误了,
return v.push(current.id) 相当于 return current.id,
并没有返回数组还是返回该值去了,那么下一个值就是一个字符串,而非数组了
刚开始为了简写直接return了, 正确的方式是分开写
const result = authors.reduce((v,current) => {
if(current.is_online){
v.push(current.id)
}
return v
}, [])
上次更新: 2021/12/19, 18:05:42