JS:Array.map不添加到数组 [英] JS: Array.map don't add to array
问题描述
我有一些我想用 Array.prototype.map
转换的数据。但是在map函数中,外部函数调用有可能引起错误。我想抓住这个错误,而不是将特定的对象添加到返回的数组。目前我只是返回未定义,然后使用 Array.prototype.filter
清除未定义的值,但这似乎是一种肮脏的方法。
要澄清,我正在寻找这个功能:
['apple' ,'pear','banana','peach']。map(function(fruit){
if(fruit ==='apple'){
return undefined;
}
返回我喜欢吃'+水果;
});
// [我喜欢吃梨,我喜欢吃桃子,我喜欢吃香蕉]
这个的任何现有实现?我只是这样做错了吗?
一个更可读的方式是;
['apple','pear','banana','peach'] filter(function(fruit){
pre>
return fruit === 'apple';
})map(function(fruit){
return'I love eating'+ fruit;
})
I have some data I'd like to transform using
Array.prototype.map
. However in the map function there is a chance of an error being thrown by an external function call. I'd like to catch this error and not add that particular object to the returned array. Currently I'm just returning undefined and then usingArray.prototype.filter
to clear out the undefined values, but this seems like a dirty way to do it.To clarify, I'm looking for this functionality:
['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']
Any existing implementatons of this? Am I just going about this the wrong way?
解决方案A more readable way would be;
['apple','pear','banana', 'peach'].filter(function(fruit) { return fruit === 'apple'; }).map(function(fruit) { return 'I love eating ' + fruit; })
这篇关于JS:Array.map不添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!