【问题标题】:how to remove the spaces in an Array?如何删除数组中的空格?
【发布时间】:2013-04-13 21:16:36
【问题描述】:

我正在尝试创建一个将单词存储在数组中的程序,我所做的是程序找到分隔符(“”或“,”)将其推入数组中,我的问题是它甚至用它存储分隔符(我必须使用数组 SEPARATORS)。

var sentence = prompt("");

var tab = [];

var word = "" ;

var separators = [" ", ","];

for(var i = 0 ; i< sentence.length ; i++){

    for(var j = 0 ; j < separators.length ; j++){

    if(sentence.charAt(i) != separators[j] && j == separators.length-1){

           word += sentence.charAt(i); 

        }else if(sentence.charAt(i) == separators[j]){

           tab.push(word);
           word = "";

        }

    }

}

tab.push(word);
console.log(tab);

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    你可以试试这个:

    var text = 'Some test sentence, and a long sentence';
    var words = text.split(/,|\s/);
    

    如果你不想要空字符串:

    var words = text.split(/,|\s/).filter(function (e) {
        return e.length;
    });
    console.log(words); //["some", "test", "sentence", "and", "a", "long", "sentence"]
    

    如果你需要使用数组你可以试试这个:

    var text = 'Some test sentence, and a long sentence',
        s = [',', ' '],
        r = RegExp('[' + s.join('') + ']+'),
        words = text.split(r);
    

    【讨论】:

    • .filter 不是必需的。只要确保你的正则表达式是贪婪的:[,\s]+。
    • 是的,它适用于 split 方法,但我必须使用我的数组(分隔符 = [“”,“,”];)
    • 试试这个:var r = new RegExp('[' + s.join('') + ']');
    【解决方案2】:

    我只会使用正则表达式:

    var words = sentence.split(/[, ]+/);
    

    如果要修复代码,请使用 indexOf 而不是 for 循环:

    for (var i = 0; i < sentence.length; i++) {
        if (separators.indexOf(sentence.charAt(i)) === -1) {
            word += sentence.charAt(i);
        } else {
            tab.push(word);
            word = "";
        }
    }
    

    【讨论】:

      【解决方案3】:

      重新检查问题后,我认为您需要结合使用原生字符串函数和 compact method from the excellent underscore library 来删除数组中的“虚假”条目:

      $('#textfield).keyup(analyzeString);
      var words;
      function analyzeString(event){
          words = [];
          var string = $('#textfield).val()
          //replace commas with spaces
          string = string.split(',').join(' ');
          //split the string on spaces 
          words = string.split(' ');
          //remove the empty blocks using underscore compact
          _.compact(words);
      }
      

      【讨论】:

      • 您能解释一下这是如何将句子拆分成单词的吗?
      • 您可以使用每个 keyUp 分析整个字符串。事实上,这可能是一种更好的方法。我会为你重写我的答案。
      猜你喜欢
      • 2023-03-08
      • 2015-03-31
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多