我有一些数据想使用 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}`)
关于javascript - JS : Array. map 不添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27110212/