美文网首页
Trailing commas in object litera

Trailing commas in object litera

作者: 从此以后dapeng | 来源:发表于2016-12-24 15:46 被阅读50次

    原文链接: 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 litera

          本文链接:https://www.haomeiwen.com/subject/ruolvttx.html