1. 对象字面值不能正确解析
问题:{a:1}.a报错,错误Uncaught SyntaxError: Unexpected token .。
解决:
({a:1}.a) // 或({a:1}).a
原因:
MDN: Object literals
An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.
简单说,就是声明对象字面值时,语句开头不应该用{,因为js解释器会认为这是语句块(block)的开始。
同理,类似问题{ name: "mc", id: 1 }会报错Uncaught SyntaxError: Unexpected token :也是这个道理。({ name: "mc", id: 1 })即可正确解析。但稍注意下,{name: "mc"}是不会报错的,它等同于name: "mc",并返回一个字符串"mc"。
2. 数字的点操作符
问题:123.toFixed(2)报错,错误Uncaught SyntaxError: Unexpected token ILLEGAL
解决:
(123).toFixed(2) //