简体   繁体   中英

Numeric keys in object gives error in Firefox (“SyntaxError: missing ; before statement”)

The object {'1':'test'} gives an error in Firefox, but seems to be fine in Chrome. Does anyone know how to get around this error and make this work? The keys and values are from an external source so I can't just change them. (Run the code snippet below in Firefox and you will see the error.)

 {'1':'test'} 

You have to save the object in a variable or use it in any way. Just writing in inside a script block does nothing.

The following works fine:

 var obj = {'1':'test'}; alert(obj['1']); 

I tried in chrome console and firefox console.

Indeed, that doesn't work in Firefox, but, it's normal.

In javascript you can't type JSON without variable declaration before.

So, Firefox doesn't understand it because javascript doesn't understand it.

In fact, I think that Chrome overrides the javascript interpretor to allow declaration without attributions.

Like in python shell when you type 5, it will write 5. So with that Chrome allow you to see the structure of an array or object whatever, just by typings them without declare it into a variable.

You can see an example here :

https://jsfiddle.net/3yqdj599/

let yes = {'1':'test'};
console.log(yes)
// {'1':'test'} => that doesn't work

Finally, don't worry, since a browser is able to execute javascript, if you assign your object in a variable, it will interpret it.

I hope this is clear and helped you ! :)

Cya !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM