为什么引用了一些对象 - 文字属性而没有引用其他属性? [英] Why are some object-literal properties quoted and others not?

查看:166
本文介绍了为什么引用了一些对象 - 文字属性而没有引用其他属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直看到这一点:声明了对象文字,使得某些键被引号括起而其他键则没有。来自jQuery 1.4.2的一个例子:

I see this all the time: object literals declared such that some keys are surrounded with quotes and others are not. An example from 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规范;所有我能找到的是[第15.12.3节的注释6,强调我的]:

I've been poking around the ECMAScript 5 specification; all I've been able to find is [Note 6 of Section 15.12.3, emphasis mine]:


注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的 stringification

However, this refers only to the stringification of JSON.

推荐答案

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

Those are Javascript reserved words, and (though not really necessary) the syntax of the language requires that they be quoted.

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

Strictly speaking, pure "JSON" notation requires that all of the "key" strings be quoted. Javascript itself however is OK with keys that are valid identifiers (but not reserved words) being unquoted.

这篇关于为什么引用了一些对象 - 文字属性而没有引用其他属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆