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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:29:26  来源:igfitidea点击:

Error "Cannot call toString on undefined" but variable is defined

javascriptundefinedtostringtypeerror

提问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 undefinedon the second line. However, I've verified via the debugger that the value of credsis 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 inloop to array. Use normal loop instead.

使用for in循环数组时应该非常小心。改用普通循环。

The array cplhas not just data but functions, so third cpin the loop is function. That's why credsturned 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