Tuesday, March 15, 2011

Javascript reserved words?

I have some JS code which generates the following object,

return {
 "type": "some thing",
 "width": 2,
 "colour": "#AA12BB",
 "values": [2,3,4]
}

The creation of this isn't a problem.

In writing the test for the method that returns this am having a problem accessing the width/type attributes: the following assertions fail (it leads to a execution/syntax error, which go away when i comment them).

assertEquals('some thing', jsonObj.type);
assertEquals(2, jsonObj.width);

while

assertEquals('#AA12BB', jsonObj.colour);

passes

Since I cannot change the key names for what I am doing, is there any way to access these values?

From stackoverflow
  • Try this:

    assertEquals('some thing', jsonObj["type"]);
    assertEquals(2, jsonObj["width"]);
    
    j pimmel : Cheers, spot on!
  • dot notation does not work with reserved words, such as "type". In that case you have to use array notation.

    Mozilla's list of Java Script Reserved words.

  • Your example works fine for me. ‘width’ and ‘type’ are not reserved words in JavaScript (although ‘typeof’ is).

    j pimmel : Weird.. you are right about them not being reserved words... But for whatever reason on FF3.0.6 it failed for me.. CSS? Firebug? Hmm, not sure
    bobince : What exactly is the error you get?

0 comments:

Post a Comment