1

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?

Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301

2 Answers2

1

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?

Community
  • 1
  • 1
Sanghyun Lee
  • 21,644
  • 19
  • 100
  • 126
  • That's new info. Why cautious? – Bart van Heukelom Jul 13 '11 at 10:17
  • +1 Within the for loop your hitting a `cpl[i]` thats a method name ., e.g `cpl["copy"]`. That sets `cp` to that methods toString() (so the string `function (start,length) ...`) which causes `creds` to be `undefined` after `creds = cp[0];` so the subsequent `creds.toString();` fails. – Alex K. Jul 13 '11 at 10:22
  • @Alex K @Sangdol Thanks for the explanation. I already knew that somewhere, but didn't think of it when I wrote the loop. Turns out that this is indeed the problem and I debugged it wrongly (inspected the value in the first iteration only, while the error is in a later one) – Bart van Heukelom Jul 13 '11 at 11:41
0

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

mastaH
  • 1,234
  • 3
  • 15
  • 30
  • `data` is an object, not an array, so I convert `creds` to a string to act as key. If it's not needed, it at least makes the intent clearer. – Bart van Heukelom Jul 13 '11 at 10:10
  • You should have specified this before. Anyway calling `toString()` on an Integer (if it is) will stop the Javascript. Have you already tried w/o it? – mastaH Jul 13 '11 at 10:14
  • 1
    you can have it data['' + creeds + ''] (those are two single quotes as in string start string end) It will cast your number to a string – TheBrain Jul 13 '11 at 10:19
  • Literal numbers don't any methods (to avoid decimal point confusion) but `var a=[1234] .. a[0].toString()` is perfectly fine – Alex K. Jul 13 '11 at 10:34
  • @Alex K Actually in another question I saw expressions like `100..toString()` and `100["toString"]()` – Bart van Heukelom Jul 13 '11 at 11:42