Javascript reserved words?

I have JS code that generates the following object,

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

Creating this is not a problem.

When writing a test for a method that returns this am, there is a problem accessing the width / type attributes: the following statements fail (this leads to a runtime / syntax error that disappears when I comment on 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 a way to access these values?

+5
source share
3 answers

Try the following:

assertEquals('some thing', jsonObj["type"]);
assertEquals(2, jsonObj["width"]);
+3
source

. " " JavaScript ( "typeof is" ).

+3

dot does not work with reserved words, such as type. In this case, you should use an array notation.

Mozilla Java Script List Reserved Words .

0
source

All Articles