在这段JavaScript错误“无法调用toString未定义”,但变量定义
creds = cp[0];
data[creds.toString()] = cp[1]; // data is an object
的镀铬给我的错误TypeError: Cannot call method toString of undefined
在第二行。不过,我通过调试器验证了creds
的值在那个点上是1400
。
发生了什么事?
在这段JavaScript错误“无法调用toString未定义”,但变量定义
creds = cp[0];
data[creds.toString()] = cp[1]; // data is an object
的镀铬给我的错误TypeError: Cannot call method toString of undefined
在第二行。不过,我通过调试器验证了creds
的值在那个点上是1400
。
发生了什么事?
使用for in
循环数组时,你应该非常谨慎。改用普通循环。
数组cpl
不只是数据而是函数,所以循环中的第三个cp
是函数。这就是为什么creds
转向未定义。
这个环节有很好的解释:Why is using "for...in" with array iteration a bad idea?
这是新的信息。为什么谨慎? –
@我添加了更多信息。 –
+1在for循环中,您可以选择一个'cpl [i]'这是一个方法名,例如'cpl [“copy”]'。这将“cp”设置为'creds = cp [0]'后导致'creds'为'undefined'的函数toString()(因此字符串'function(start,length)...')' 'creds.toString();'失败。 –