我有一些数据想要使用Array.prototype.map
进行转换。但是在map函数中,外部函数调用可能会抛出错误。我想捕获此错误并不将该特定对象添加到返回的数组中。目前,我只返回undefined,然后使用Array.prototype.filter
清除undefined值,但这似乎是一种不太好的方法。
为了澄清,我要实现的功能是:
['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']
有任何现有的实现吗?我是不是走错了方向?
.map()
方法,而不是Javascript的方法。 - Barmar