Javascript 如何跳过数组 .map 的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35357202/
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-08-23 17:37:56  来源:igfitidea点击:

How I can skip the element of array .map?

javascriptnode.js

提问by Sumit Aggarwal

var userids = userbody.contacts.map(function(obj){

  if((obj.iAccepted=='true')&&(obj.contactAccepted=='true')) {
    console.log(true);
    return obj.userID //return obj.userID
  } 

});

This will give the result like this:

这将给出如下结果:

[ '0', '35', '37', '30', '34', '36', '33', '32', undefined, '332', '328', '337', '333', undefined ]

[ '0', '35', '37', '30', '34', '36', '33', '32', 未定义, '332', '328', '337', '333' , 不明确的 ]

I want to skip the undefined elements in the array.

我想跳过数组中未定义的元素。

回答by Z4-

This is what Array.prototype.filter()is for. You need to do this in two steps.

Array.prototype.filter()就是为了。您需要分两步执行此操作。

var userids = userbody.contacts
    .filter(contact => contact.iAccepted == 'true' && contact.contactAccepted == 'true')
    .map(contact => contact.userId);

The filter part takes out all unnecessary elements, then map converts the rest to the way you want.

filter 部分去掉所有不需要的元素,然后 map 把剩下的转换成你想要的方式。

回答by Shanoor

You can filter out the false values:

您可以过滤掉错误值:

userids = userids.filter((i) => i);

Or, if you can't use arrow functions:

或者,如果您不能使用箭头函数:

userids = userids.filter(function(i) { return i; });

回答by William

Not sure if this is what you're looking for:

不确定这是否是您要查找的内容:

var arr = [true,true,false,true,false];


var result = arr.map(function(val,ind,arr){

        if(val === !false){
          return val
        }
})

console.log(result) // true, true , true

https://jsfiddle.net/horonv8a/

https://jsfiddle.net/horonv8a/