javascript 错误“无法在未定义时调用 toString”但变量已定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6677165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error "Cannot call toString on undefined" but variable is defined
提问by Bart van Heukelom
In this piece of Javascript
在这段 Javascript 中
creds = cp[0];
data[creds.toString()] = cp[1]; // data is an object
Chrome gives me the error TypeError: Cannot call method toString of undefined
on the second line. However, I've verified via the debugger that the value of creds
is at that point the number 1400
.
ChromeTypeError: Cannot call method toString of undefined
在第二行给了我错误。但是,我已经通过调试器验证了此时的值creds
是 number 1400
。
What's going on?
这是怎么回事?
采纳答案by Sanghyun Lee
You should be very cautious when using for in
loop to array. Use normal loop instead.
使用for in
循环数组时应该非常小心。改用普通循环。
The array cpl
has not just data but functions, so third cp
in the loop is function. That's why creds
turned to undefined.
数组cpl
不仅有数据还有函数,所以cp
循环中的第三个是函数。这就是为什么creds
转向未定义。
This link has good explanation: Why is using "for...in" with array iteration a bad idea?
这个链接有很好的解释:为什么在数组迭代中使用“for...in”是个坏主意?
回答by mastaH
Javascript don't need variable type so do it by removing toString()
.
Javascript 不需要变量类型,所以通过删除toString()
.
btw I'm not sure you can call toString()
on a primitive type as int
顺便说一句,我不确定您是否可以调用toString()
原始类型作为int