Are trailing commas in arrays and objects part of the spec?

Are trailing commas standard in JavaScript, or do most browsers like Chrome and Firefox just tolerate them?

I thought they were standard, but IE8 puked after encountering one—of course IE not supporting something hardly means it's not standard.

Here's an example of what I mean (after the last element of the books array):

var viewModel = {
    books: ko.observableArray([
        { title: "..", display: function() { return ".."; } },
        { title: "..", display: function() { return ".."; } },
        { title: "..", display: function() { return ".."; } }, // <--right there
    ]),
    currentTemplate: ko.observable("bookTemplate1"),
    displayTemplate: function() { return viewModel.currentTemplate(); }
};

Specs: ECMAScript 5 and ECMAScript 3


Section 11.1.5 in the ECMAScript 5 specification:

ObjectLiteral :
    { }
    { PropertyNameAndValueList }
    { PropertyNameAndValueList , }

So yes, it is part of the specification.

Update: Apparently this is new in ES5. In ES3 (page 41), the definition was just:

ObjectLiteral :
    { }
    { PropertyNameAndValueList }

For arrays literals (Section 11.1.4) it is even more interesting ( Update: this already existed in ES3):

ArrayLiteral :
    [ Elisionopt ]
    [ ElementList ]
    [ ElementList , Elision_opt ]

(where Elision_opt is Elisionopt, meaning the Elision is optional)

Elision is defined as

Elision :
    ,
    Elision ,

So, an array literal like

var arr = [1,2,,,,];

is perfectly legal. This creates an array with two elements but sets the array length to 2 + 3 = 5 .

Don't expect too much from IE (before IE9)...


Just a quick reminder/warning that this is one of the areas in which the JavaScript/ECMAScript standard and JSON standard differ; trailing commas are valid in JS but not valid in JSON.


What is even funnier, IE7 gives

[1,].length  --> 2

while Firefox and Chrome

[1,].length  --> 1
链接地址: http://www.djcxy.com/p/27276.html

上一篇: 如何在LINUX中实现AJAX(交互式)类SEARCH查找文件?

下一篇: 数组和对象中的尾随逗号是规范的一部分吗?