最近在使用map的过程中发现有时会返回一个含undefined的数组,在此记录一下
先上代码
let arr = [
{
name: 'a',
id: 1
},
{
name: 'b',
id: 2
},
{
name: '',
id: 3
},
{
name: 'c',
id: 4
},
];
arr = arr.map((item) => {
if (item.name) {
return item;
}
})
console.log(arr);
本意是想返回一个都是有效名字的对象数组,结果不符要求的元素变成了undefined
原因:
因为map方法总需要有返回值 ,当返回 undefined 或没有返回任何内容时,返回值将是undefined
因此我们不能用map生成一个与其长度不等的数组
MDN
如果有以下情形,则不该使用
map
:
- 你不打算使用返回的新数组;或
- 你没有从回调函数中返回值。
解决方案:
- 用 filter 配合或代替 map