Why leave a trailing comma after a key value pair in an object literal?

烈酒焚心 提交于 2019-12-08 10:12:08

问题


I was looking at gruntjs and I looked at some JSON examples used to configure Grunt tasks.

Here is an example of the JSON:

grunt.initConfig({
  concat: {
    foo: {
      // concat task "foo" target options and files go here.
    },
    bar: {
      // concat task "bar" target options and files go here.
    },
  },
  uglify: {
    bar: {
      // uglify task "bar" target options and files go here.
    },
  },
});

As you can see, there is an 'extra' comma after each of the bar properties. I tried this notation in Chrome and it is valid. Although it is valid, I wouldn't use this notation but why would people use it?


回答1:


I tried this notation in Chrome and it is valid.

Simply because it works in Chrome doesn't mean it's valid. It is valid because the spec says so :-)

I wouldn't use this notation but why would people use it?

To make copy&pasting easier. You can just append new properties without caring additional work. It's a bad practice in program code because older browsers (notably IE) and the ES3 spec disallow them, but in a config file (i.e. in a known environment) it makes life easier.



来源:https://stackoverflow.com/questions/18116439/why-leave-a-trailing-comma-after-a-key-value-pair-in-an-object-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!