Trailing commas in object literals and array literals

原文链接: http://www.2ality.com/2013/07/trailing-commas.html

在ECMAScript 5中,对象文字中的尾随逗号是合法的,数组中的尾逗点将被忽略。

Trailing commas in object literals

Thus, if you can afford to ignore older JavaScript engines, you can write your object literals like this:

    var obj = {
        first: 'Jane',
        last: 'Doe',
        age: 40,  // trailing comma
    };```
The advantage of adding a trailing comma is that you can rearrange the innards of the literal without having to worry about commas being in the right places.

### Trailing commas in array literals
Similarly, trailing commas in arrays are ignored:
    > var arr = [ 'a', 'b', 'c', ];
    > arr
    [ 'a', 'b', 'c' ]
    > arr.length
    3
This goes so far that you need to write two trailing commas if you want to add a trailing hole [1]:
    > var arr = [ 'a', 'b', , ];
    > arr.length
    3

### Trailing commas in JSON
JSON [2] is based on JavaScript’s syntax prior to ECMAScript 5, which means that trailing commas are illegal:
JSON [2]基于JavaScript的ECMAScript 5之前的语法,这意味着尾随逗号是非法的:
    > JSON.parse('{"x":1,}')
    SyntaxError: Unexpected token }
    > JSON.parse('[1,]')
    SyntaxError: Unexpected token ]

### What browsers support object literals with trailing commas?
Most browsers support object literals with trailing commas. You are only out of luck in Internet Explorer 8 and earlier (compatibility table).

你可能感兴趣的:(Trailing commas in object literals and array literals)