Error "Cannot call toString on undefined" but variable is defined
In this piece of 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
.
What's going on?
You should be very cautious when using for in
loop to array. Use normal loop instead.
The array cpl
has not just data but functions, so third cp
in the loop is function. That's why creds
turned to undefined.
This link has good explanation: Why is using "for...in" with array iteration a bad idea?
Javascript don't need variable type so do it by removing toString()
.
btw I'm not sure you can call toString()
on a primitive type as int
精彩评论