开发者

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

开发者 https://www.devze.com 2023-03-19 18:25 出处:网络
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. How

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号