[英]JS: Array.map don't add to array
我有一些数据想要使用Array.prototype.map
进行转换。 但是,在 map 函数中,外部函数调用可能会引发错误。 我想捕获此错误,而不是将该特定对象添加到返回的数组中。 目前我只是返回 undefined 然后使用Array.prototype.filter
清除未定义的值,但这似乎是一种肮脏的方法。
为了澄清,我正在寻找此功能:
['apple','pear','banana', 'peach'].map(function(fruit){
if (fruit === 'apple') {
return undefined;
}
return 'I love to eat ' + fruit;
});
// ['I love to eat pear', 'I love to eat peach', 'I love to eat banana']
任何现有的实现? 我只是以错误的方式解决这个问题吗?
一种更具可读性的方式是;
['apple','pear','banana', 'peach'].filter(function(fruit) {
return fruit === 'apple';
}).map(function(fruit) {
return 'I love eating ' + fruit;
})
带有箭头函数和模板字符串;
['apple','pear','banana', 'peach']
.filter(fruit => fruit === 'apple')
.map(fruit => `I love eating ${fruit}`)
如果您不想使用简单的for
循环,那么请尝试以这种方式使用reduce
代替map
:
var result = ['apple','pear','banana', 'peach'].reduce(function(prev, curr){ if (curr === 'apple') { return prev; } prev.push(curr); return prev; }, []); alert(result);
所以这个想法是,在“异常”的情况下,您只需返回prev
数组而不修改它。
我最终在Array
原型上将这两种方法合并为一种。 正如@Benmj 提到的,您也可以将其放在自定义实用程序库中。
Array.prototype.mapDefinedValues = function(handler) {
return this.map(function(item){
return handler(item);
}).filter(function(item){
return item !== undefined;
});
}
Mozilla 的 MDN for Array.prototype.map() 说使用forEach或for-of :
由于 map 构建了一个新数组,因此在不使用返回的数组时使用它是一种反模式; 使用 forEach 或 for-of 代替。
如果出现以下情况,您不应该使用地图:
你没有使用它返回的数组; 和/或您没有从 callback 返回值。
正如评论中所述,您应该将其与过滤器结合使用。 幸运的是,这很容易,因为您可以链接数组方法:
['apple','pear','banana', 'peach'].map(function(fruit){
if (fruit === 'apple') {
return undefined;
}
return 'I love to eat ' + fruit;
}).filter(function (item) { return item; });
像这样的函数式编程的租户之一是,您可以创建没有副作用的简单构建块。 OP 所描述的本质上是向.map
添加副作用,这种行为不应该被劝阻。
上面的答案可以进一步简化。
这个代码片段实际上可以进一步减少。 如果可以,请始终避免推入数组。
var result = ['apple','pear','banana', 'peach'].reduce(function(prev, curr){
if (curr === 'apple') {
return prev;
}
return prev.concat(curr);
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.