【问题标题】:Remove white spaces in the elements of an array删除数组元素中的空格
【发布时间】:2018-04-18 02:49:53
【问题描述】:

有没有办法从javascript中的数组中删除所有空格。例如:[' 1',' ','c ']; 应替换为 ['1','c'];。这个https://stackoverflow.com/a/20668919/4877962 删除了作为空格的元素,但是如何删除元素中存在的空格,即' 1''1'?我是JS的新手,如果这是一个愚蠢的问题,请忽略。

【问题讨论】:

  • 遍历数组并修剪每个字符串。然后您可以使用您找到的解决方案来摆脱空字符串。一旦您对 JS 更加熟悉,您就可以将这两个操作合并到一个 reduce 中,以便在一次迭代中完成它。

标签: javascript arrays


【解决方案1】:

如果你只想从每个字符串中删除所有空格,你可以使用

['  1',' ','c  '].map(item => item.trim())

如果您想删除所有空格和空字符串,您可以尝试 pigeontoe 解决方案或这种减少实现

const array = ['  1',' ','c  ']

const result = array.reduce((accumulator, currentValue) => {
    const item = currentValue.trim()

    if (item !== '') {
        accumulator.push(item);
    }

    return accumulator;
}, [])

【讨论】:

    【解决方案2】:

    Javascript 有trim() 函数https://www.w3schools.com/jsref/jsref_trim_string.asp。使用可以使用map循环遍历数组和trim()每个元素。

    【讨论】:

      【解决方案3】:

      您可以结合使用 .map() 和 .trim() 来遍历数组并删除空格。然后 .filter() 像这样过滤掉空字符串:

      const input = ['  1',' ','c  '];
      
      const output = input
        .map(val => val.trim())
        .filter(val => val !== '')
      
      console.log(output)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-06
        • 2011-04-08
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 2018-08-06
        • 2013-01-26
        相关资源
        最近更新 更多