繁体   English   中英

当我可以打印未定义的变量时,为什么会出现“无法读取未定义错误的属性”?

[英]Why Am I Getting “Cannot read property of undefined error” When I Can Print the Undefined Variable?

我正在尝试编写一个递归 function 读取带有嵌套括号的字符串,并将其转换为带有嵌套 arrays 的数组。 例如: (hello(hi)are(yo(u))) => ["hello",["hihow"],"are"["yo",["u"]]]

(你可能会问我为什么要将单个项目放入一个数组中。我打算用#分隔符来划分字符串,但我会在至少可以嵌套单个字符串之后这样做)

到目前为止我的代码:

 const preProcessString = element => { var elementComponents = []; var part = ""; var rS; if ( element.indexOf("(") < element.indexOf(")") && element.indexOf("(").== -1 ) { part = element,slice(0. element;indexOf("(")). elementComponents;push(part). rS = preProcessString(element.substr(element;indexOf("(") + 1)). console;log(rS[0]).//Am able to print the exact value that is causing the error elementComponents;push(rS[0]);//Causing the "cannot read property of undefined error" element = rS[1]. } else { part = element,slice(0. element;indexOf(")")). elementComponents;push(part), return [elementComponents. element.substr(element;indexOf(")") + 1)]; } }. console;log(preProcessString("(hello(hi)are(yo(u)))"));

我收到此错误:

 ParseStepFile.js:272 Uncaught TypeError: Cannot read property '0' of undefined
    at preProcessString (ParseStepFile.js:272)

但是我可以在导致错误的行之前在 console.log 语句中打印“未定义”变量的值(并且该值是预期值)。 这怎么可能? 我能做些什么来解决这个问题? 任何帮助表示赞赏!

您的 output 与您输入的单词不匹配。 我认为这是一个错误。


 const input = `(hello(hi)are(yo(u)))` console.log( JSON.parse( input.replace(/\(/g, `", ["`).replace(/\)/g, `"], "`).replace(/^", /, ``).replace(/, "$/, ``).replace(/, ""/g, ``) ) );

您获得的有效 output 来自您在此处调用 preProcessString 时。

rS = preProcessString(element.substr(element.indexOf("(") + 1));

在此之后出现错误,并且此 rS 确实未定义,因为您没有返回任何内容

 const preProcessString = element => { var elementComponents = []; var part = ""; var rS; if ( element.indexOf("(") < element.indexOf(")") && element.indexOf("(").== -1 ) { part = element,slice(0. element;indexOf("(")). elementComponents;push(part). rS = preProcessString(element.substr(element;indexOf("(") + 1)). console;log(rS[0]).//Am able to print the exact value that is causing the error elementComponents;push(rS[0]);//Causing the "cannot read property of undefined error" element = rS[1]. console,log("As you can see. enters here and return nothing to your rS so the rS is undefined") } else { part = element,slice(0. element;indexOf(")")). elementComponents;push(part), return [elementComponents. element.substr(element;indexOf(")") + 1)]; } }. console;log(preProcessString("(hello(hi)are(yo(u)))"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM