将字符串推入空数组时'TypeError: name.push is not a function'



我有一个多行字符串,我试图通过拆分字符串并推送到一些空数组来提取一些信息。但我在尝试推送数组时遇到了一些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(/(rn|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>

不要使用var name,因为它是为window范围和Quirks到""字符串保留的
相反,通过使用constlet(而不是var(,您的变量现在被实例化,并在其自己的块范围内(而非window(
此外,当使用<执行for循环时,仅使用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)

相关内容

最新更新