javascript JS:Array.map 不添加到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27110212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:57:18  来源:igfitidea点击:

JS: Array.map don't add to array

javascriptarraysmap

提问by jtmarmon

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.filterto clear out the undefined values, but this seems like a dirty way to do it.

我有一些数据想使用Array.prototype.map. 但是,在 map 函数中,外部函数调用可能会引发错误。我想捕获此错误,而不是将该特定对象添加到返回的数组中。目前我只是返回 undefined 然后Array.prototype.filter用来清除未定义的值,但这似乎是一种肮脏的方法。

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?

任何现有的实现?我只是以错误的方式解决这个问题吗?

回答by Renato Gama

A more readable way would be;

一种更具可读性的方式是;

['apple','pear','banana', 'peach'].filter(function(fruit) {
    return fruit === 'apple';
}).map(function(fruit) {
    return 'I love eating ' + fruit; 
})

回答by dfsq

If you don't want to use simple forloop, then instead of maptry to use reducethis way:

如果你不想使用简单的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);

So the idea is that in case of "exception" you simply return prevarray without modifying it.

所以这个想法是,在“异常”的情况下,您只需返回prev数组而不修改它。

回答by jtmarmon

I ended up merging the two methods together into one on the Arrayprototype. As @Benmj mentioned, you could alternatively put this in a custom utility lib.

我最终在Array原型上将这两种方法合二为一。正如@Benmj 提到的,您也可以将其放在自定义实用程序库中。

Array.prototype.mapDefinedValues = function(handler) {
  return this.map(function(item){
    return handler(item);
   }).filter(function(item){
    return item !== undefined;
   });
}

回答by user3371805

Mozilla's MDN for Array.prototype.map() says to use forEachor for-offor that:

Mozilla 的 MDN for Array.prototype.map() 说要使用forEachfor-of

Since map builds a new array, using it when you aren't using the returned array is an anti-pattern; use forEach or for-of instead.

You shouldn't be using map if:

you're not using the array it returns; and/or you're not returning a value from the callback.

由于 map 构建了一个新数组,因此在不使用返回的数组时使用它是一种反模式;使用 forEach 或 for-of 代替。

如果出现以下情况,您不应该使用地图:

你没有使用它返回的数组;和/或 您没有从 callback 返回值

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#When_not_to_use_map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#When_not_to_use_map

回答by user3619165

The answer above can be reduced even further.

上面的答案可以进一步简化。

This code snippet can actually be reduced even further. Always avoid pushing into array if you can imo.

这个代码片段实际上可以进一步减少。如果可以,请始终避免推入数组。

var result = ['apple','pear','banana', 'peach'].reduce(function(prev, curr){
   if (curr === 'apple') {
     return prev;
   }
   return prev.concat(curr);
  }, []);

回答by Benmj

As was stated in the comments, you should combine this with a filter. Luckily, this is easy because you can chain array methods:

正如评论中所述,您应该将其与过滤器结合使用。幸运的是,这很容易,因为您可以链接数组方法:

['apple','pear','banana', 'peach'].map(function(fruit){
     if (fruit === 'apple') {
         return undefined;
     }
     return 'I love to eat ' + fruit;
}).filter(function (item) { return item; });

update

更新

One of the tenants of functional programming like this is that you create simple building blocks that do not have side effects. What the OP is describing is essentially adding a side-effect to .map, and this type of behavior should be discouraged.

像这样的函数式编程的租户之一是,您可以创建没有副作用的简单构建块。OP 所描述的本质上是向 增加了副作用.map,应该劝阻这种类型的行为。