JS:Array.map不添加到数组 [英] JS: Array.map don't add to array

查看:153
本文介绍了JS:Array.map不添加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些我想用 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){
return fruit === 'apple';
})map(function(fruit){
return'I love eating'+ fruit;
})
pre>

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 using Array.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆