代码之家  ›  专栏  ›  技术社区  ›  Anu

将字符串推入空数组时出错`Type Error`

  •  0
  • Anu  · 技术社区  · 4 年前

    我有一个多行字符串,我正试图通过拆分字符串并推送到一些空数组来提取一些信息。但我正在吃 type error 在尝试推送阵列时。我的代码如下。我在堆栈溢出方面做了一些研究,建议将数组 [] {} . 但我不要字典。有人能帮忙吗?

    < script >
      var str = `PP 0800 / 00 / XX: Units: 2: Total: 4.70 || 
      PP 0800 / 00 / XX: Units: 1: Total: 2.35 ||` //This is the multi line string
    
      var singleLine = str.replace(/(\r\n|\n|\r)/gm, ""); //Converting multi line string into a single line
      var splittedArray = singleLine.split("||"); //splitting the string based on the symbol ||
    
      var name = []; //Initializing three empty arrays
      var unit = [];
      var total = [];
      for (i = 0; i < splittedArray.length - 1; i++) { //Looping through the splittedArray
        var furtherSplit = splittedArray[i].split(":"); //Splitting each array further based on the symbol :
        name.push(furtherSplit[0]); //This is where name, unit and total pushing into three separate arrays
        unit.push(furtherSplit[2]);
        total.push(furtherSplit[4]);
        //    alert(furtherSplit[0]); //This is showing the name correctly
      }
    </script>
    1 回复  |  直到 4 年前
        1
  •  1
  •   Roko C. Buljan    4 年前

    不要使用 var name window 适用范围和特殊要求 ""
    相反,通过使用 const let ,(而不是 var )您的变量现在被实例化并在它自己的块范围内(不是 窗口
    另外,当你和 < 使用just length ,不是 length - 1

    const str = `PP 0800 / 00 / XX: Units: 2: Total: 4.70 || 
      PP 0800 / 00 / XX: Units: 1: Total: 2.35 ||`;
    
    const lines = str.split(/\n/);
    const name = []; 
    const unit = [];
    const total = [];
    
    for (let i = 0; i < lines.length; i++) { 
      const parts = lines[i].replace("||", "").split(":");
      name.push(parts[0].trim()); 
      unit.push(parts[2].trim());
      total.push(parts[4].trim());
    }
    
    console.log(name, unit, total)