jtm*_*mon 9 javascript arrays map
我有一些我想要转换的数据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']
Run Code Online (Sandbox Code Playgroud)
这个的任何现有的实现?我只是以错误的方式解决这个问题吗?
Ren*_*ama 11
一种更易读的方式是;
['apple','pear','banana', 'peach'].filter(function(fruit) {
return fruit === 'apple';
}).map(function(fruit) {
return 'I love eating ' + fruit;
})
Run Code Online (Sandbox Code Playgroud)
如果您不想使用简单for循环,那么请map尝试使用reduce这种方式:
var result = ['apple','pear','banana', 'peach'].reduce(function(prev, curr){
if (curr === 'apple') {
return prev;
}
prev.push(curr);
return prev;
}, []);
alert(result);Run Code Online (Sandbox Code Playgroud)
所以我的想法是,在"异常"的情况下,你只需返回prev数组而不修改它.
| 归档时间: |
|
| 查看次数: |
13249 次 |
| 最近记录: |