我经常看到这种情况:对象字面量的声明使得一些键用引号括起来,而另一些则没有。一个来自 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"
};
将前两个属性键(for
和 class
)用引号括起来有什么意义无报价?有什么区别吗?
我一直在寻找 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/