[英]'TypeError: name.push is not a function' while pushing a string into an empty array
I have a multi line string which I am trying to extract some information by splitting the string and push to some empty arrays.我有一个多行字符串,我试图通过拆分字符串来提取一些信息并推送到一些空的 arrays。 But I am having some
type error
while trying to push array.但是我在尝试推送数组时遇到了一些
type error
。 My code as below.我的代码如下。 I did some research in stack overflow and some suggestion is to put the array
[]
as dictionary {}
.我对堆栈溢出做了一些研究,一些建议是将数组
[]
作为字典{}
。 But I don't want any dictionary.但我不想要任何字典。 Can someone help?
有人可以帮忙吗?
< 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>
Don't use var name
since it's reserved for the window
scope and Quirks to ""
String.不要使用
var name
,因为它是为window
scope 和 Quirks to ""
String 保留的。
In contrast, by using const
, let
, (instead of var
) your variables are now instantiated and inside its own block scope (not window
).相反,通过使用
const
, let
,(而不是var
)你的变量现在被实例化并在它自己的块 scope (不是window
)内。
Also, when you do a for loop with <
use just length
, not length - 1
此外,当您使用
<
执行 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.