简体   繁体   English

即使条件不成立,地图函数也会返回项目

[英]map function returns item even if condition is not true

Here's my code: 这是我的代码:

//input = aaaaaaa,                ddd,            ,    
 asdsad,

newUser =
users
  .split(',')
  .map(item => {
    item = item.trim();
    if(item.length > 0) {
      return item;
    }
}).join();

//output = aaaaaaa,ddd,,asdsad,

So my question is why if item has 0 length is returned from map function? 所以我的问题是为什么从地图函数返回项目是否具有0长度? Am I missing something obvious? 我是否缺少明显的东西?

//EDIT: //编辑:

Yeah, now its removoing empty strings but what about white spaces? 是的,现在它删除了空字符串,但是空白呢? My result still looks like this: 我的结果仍然看起来像这样:

asdasdasd , aa

I want to have: 我希望有:

asdasdasd,aa

As per doc of .map() 根据.map()的文档

The map() method creates a new array with the results of calling a provided function on every element in the calling array. map()方法创建一个新数组,并在调用数组中的每个元素上调用提供的函数。

So using map you can perform some opration on each element, you can not omit any element. 因此,使用map可以对每个元素执行一些操作,而不能省略任何元素。

If you want to omit some element based on some condtion then use .filter() . 如果要基于某些条件忽略某些元素,请使用.filter()

For your case you can first use map() for triming all element then use filter() to removed element whose length is not >0 . 对于您的情况,您可以首先使用map()修剪所有元素,然后使用filter()删除长度不>0元素。

 var input = "aaaaaaa, ddd, ,asdsad "; var output = input.split(',').map(item => { item = item.trim(); return item; }).filter(item => { return item.length > 0; }).join(); console.log(output); 

The length of the array returned by map() will always be equal to the length of orignal array. map()返回的数组的length将始终等于原始数组的长度。 When you want to remove elements of array accoring to condition use filter() . 如果要根据条件删除数组元素,请使用filter()

In the particular case you can remove white spaces first from the string and then remove two or more adjacent commas with single comma. 在特殊情况下,您可以先从字符串中删除空格,然后再用单个逗号删除两个或多个相邻逗号。

 let input = 'aaaaaaa, ddd, , asdsad,' let res = input.replace(/\\s+/g,'').replace(/,{2,}/,','); console.log(res) 

You can use String replace and regex to remove all white space 您可以使用String replace和regex删除所有空白

 let input = 'aaaaaaa, ddd, , asdsad,'; let newData = input.replace(/ /g, '');; console.log(newData) 

Alternatively you can use reduce function. 另外,您可以使用减少功能。 Inside reduce callback check the the length of the string and if condition satisfies then push it with the accumulator. 在reduce回调内部,检查字符串的长度,如果条件满足,则用累加器将其压入。 Finally use join to cancat using , delimiter 最后使用join使用到cancat ,分隔符

 let users = " aaaaaaa, ddd, , asdsad" let newUser = users.split(',') .reduce(function(acc, curr) { if (curr.trim().length > 0) { acc .push(curr.trim()); } return acc; },[]).join(',') console.log(newUser) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM