javascript - 为什么有些对象文字属性被引用而有些则没有?

标签 javascript json quotes object-literal

我经常看到这种情况:对象字面量的声明使得一些键用引号括起来,而另一些则没有。一个来自 jQuery 1.4.2 的例子:

jQuery.props = {
    "for": "htmlFor",
    "class": "className",
    readonly: "readOnly",
    maxlength: "maxLength",
    cellspacing: "cellSpacing",
    rowspan: "rowSpan",
    colspan: "colSpan",
    tabindex: "tabIndex",
    usemap: "useMap",
    frameborder: "frameBorder"
};

将前两个属性键(forclass)用引号括起来有什么意义无报价?有什么区别吗?

我一直在寻找 ECMAScript 5 specification ;我所能找到的只是 [第 15.12.3 节的注 6,重点是我的]:

NOTE 6 An object is rendered as an opening left brace followed by zero or more properties, separated with commas, closed with a right brace. A property is a quoted String representing the key or property name, a colon, and then the stringified property value. An array is rendered as an opening left bracket followed by zero or more values, separated with commas, closed with a right bracket.

不过,这里只指JSON的字符串化

最佳答案

这些是 Javascript 保留字,并且(虽然不是真的必要)语言的语法要求它们被引用。

严格来说,纯“JSON”表示法要求所有的“键”字符串都被引用。然而,Javascript 本身可以使用不带引号的有效标识符(但不是保留字)的键。

关于javascript - 为什么有些对象文字属性被引用而有些则没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2348867/

相关文章:

javascript - 三.js 中 Canvas 上的 IP 摄像机流

javascript - 使用 $http 在 AngularJS 中执行 AQL

javascript - Ajax 错误重定向

jquery - 为什么我的 jQuery jEditable、就地编辑回调不起作用?

mysql - 何时在 MySQL 中使用单引号、双引号和反引号

javascript - 预期 while 循环内的点击事件 - jquery/javascript

json - 如何使用 Azure CLI 筛选 JMESPath 中的元素数组

json - Martini 中的 JSON 编码错误

php - mysql 选择带有转义引号的记录

mysql - MySQL 中何时使用单引号、双引号和反引号