我有一些数据想要使用Array.prototype.map
。但是,在映射函数中,外部函数调用可能会引发错误。我想捕获此错误,并且不将该特定对象添加到返回的数组中。目前我只是返回未定义然后使用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}`)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)