【问题标题】:JS convert delimiter separated string to array elementsJS将分隔符分隔的字符串转换为数组元素
【发布时间】:2016-04-29 21:07:57
【问题描述】:

只是为了好玩,我写了一个快速脚本来接收一个逗号分隔字符的字符串,我使用逗号来表示一个不同的单词,然后我输出一个以单词为元素的数组。我的问题在于我的逻辑 - 这仅适用于原始字符串中的逗号。

发生的情况是该算法仅查看我在调用函数时提供的分隔符数组中的第一个元素(逗号)。我正在考虑在某处使用布尔值作为标志,但不确定这是否真的是最好的方法。有什么建议吗?

var stringToArray = function(delimiterArray, originalString) {
  var arrayOutput = []
  var tempWord = ""
  for (var i = 0; i < originalString.length; i++) {

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

      var currentCharacter = originalString.charAt(i)
      var currentDelimiter = delimiterArray[j]

      while (currentCharacter != currentDelimiter) {
        tempWord += currentCharacter
          //once we hit a delimiter, break so that we can move onto the next conditional statement. 
        break
      }

      if (currentCharacter === currentDelimiter) {
        //push word onto the array to hold each string, and then break out so we can go back to the iteration of the nested loops
        arrayOutput.push(tempWord)
        tempWord = ""
        break
      }

      //we break out of the second for loop -> 
      break
    }

  }
  return arrayOutput
}

delims = [',', '.', ';', ' ']
originalString = "USA,Canada,Mexico,Bermuda,Grenada,Belize"

finalOutput = stringToArray(delims, originalString)
console.log(finalOutput)

如果我使用 '.'作为我用作参数的字符串中的分隔符,我的算法失败了。我在 C 中使用布尔标志(很久以前)实现了这个,我必须编写更多代码,因为我没有使用任何内置函数(必须找到所有内容的长度,以便我可以为数据结构分配足够的内存存储东西)。不过,不想重新访问那个旧代码。

【问题讨论】:

  • Javascript 已经有一个 split() 函数来执行此操作。此外,如果您想在数组中搜索某些内容,可以使用indexOf() 而不是编写自己的循环。
  • @Barmar 是的,完全清楚。如第一行所述,这只是为了好玩。我想自己实现。
  • 您的while() 循环永远不会修改currentCharactercurrentDelimiter,因此它将永远循环。
  • 但是由于它有一个break 来防止循环,所以它实际上只是一个if() 语句。你为什么用while
  • 为什么要把事情复杂化 -> jsfiddle.net/0hbmgbuy

标签: javascript string algorithm logic delimiter


【解决方案1】:

问题在于,如果当前字符与当前分隔符不匹配,则将其添加到 tempWord。因此,如果当前字符与第一个分隔符不匹配,则会将其添加到 tempWord,即使它可能与其他分隔符之一匹配。您需要遍历整个分隔符数组才能确定字符是否为分隔符。

var stringToArray = function(delimiterArray, originalString) {
  var arrayOutput = [];
  var tempWord = "";
  for (var i = 0; i < originalString.length; i++) {
    var currentCharacter = originalString.charAt(i)
    var isDelimiter = false;
    for (var j = 0; j < delimiterArray.length; j++) {

      var currentDelimiter = delimiterArray[j]

      if (currentCharacter == currentDelimiter) {
        isDelimiter = true;
        //once we hit a delimiter, break so that we can move onto the next conditional statement. 
        break;
      }

    }
    if (isDelimiter) {
      arrayOutput.push(tempWord);
      tempWord = "";
    } else {
      tempWord += currentCharacter;
    }

  }
  return arrayOutput;
}

delims = [',', '.', ';', ' ']
originalString = "USA,Canada.Mexico,Bermuda,Grenada,Belize"

finalOutput = stringToArray(delims, originalString)
console.log(finalOutput)

出于某种原因,这似乎是人们编写自己的数组搜索代码时非常常见的错误。

【讨论】:

  • 现在很有意义哈哈。感谢您的帮助!
【解决方案2】:

这是一个更正后的脚本,对更改进行了注释:

var stringToArray = function(delimiterArray, originalString) {
  var arrayOutput = []
  var tempWord = ""
  for (var i = 0; i < originalString.length; i++) {
    // Set currentCharacter here, as it does not depend on j:
    var currentCharacter = originalString.charAt(i)

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

      var currentDelimiter = delimiterArray[j]

      if (currentCharacter === currentDelimiter) {
        //push word onto the array to hold each string, and then break out so we can go back to the iteration of the nested loops
        arrayOutput.push(tempWord)
        tempWord = ""
        break
      }

      //No, we don't break out of the second for loop -> 
    }

    // Moved out of the j-loop, and turned into an IF without BREAK:
    if (currentCharacter != currentDelimiter) {
      tempWord += currentCharacter
    }

  }
  return arrayOutput
}

var delims = [',', '.', ';', ' ']
var originalString = "USA,Canada,Mexico,Bermuda,Grenada,Belize"

var finalOutput = stringToArray(delims, originalString)
document.write(JSON.stringify(finalOutput))    

【讨论】:

    【解决方案3】:

    你有几个问题:

    • 您在 while 循环中使用了中断。这什么也没做,它跳出了 while 循环,而不是上层循环。
    • for 循环末尾的 break 没有任何作用,它跳出了 for 循环。
    • 您遗漏了最后一个单词,您需要将其推送到最后的数组中。
    • 我已将分隔符检查拆分为isDeliminator() 函数。这使代码更清晰、更模块化(您可以再次使用它)并且通常会减少错误。

    下面是我的代码。

    function stringToArray(delimiterArray, originalString) {
          var arrayOutput = [];
          var tempWord = '';
          for (var i = 0; i < originalString.length; i++) {
    
              var currentCharacter = originalString.charAt(i);
    
              if (isDeliminator(currentCharacter)) {
                  //push word onto the array to hold each string, and then break out so we can go back to the iteration of the nested loops
                  arrayOutput.push(tempWord);
                  tempWord = '';
              } else {
                  tempWord += currentCharacter;
              }
    
          }
    
          // Push the last work onto the array
          arrayOutput.push(tempWord);
    
          return arrayOutput;
    }
    
    function isDeliminator(char) {
        for (var i = 0; i < delims.length; i += 1) {
            if (char === delims[i]) {
                return true;
            }
        }
        return false;
    }
    
    var delims = [',', '.', ';', ' '];
    var inputString = 'USA.Canada,Mexico;Bermuda,Grenada,Belize';
    var finalOutput = stringToArray(delims, inputString);
    console.log(finalOutput);

    【讨论】:

      猜你喜欢
      • 2019-08-23
      • 2015-01-22
      • 2010-10-19
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多