简体   繁体   English

JS中的对象文字表示法差异

[英]Object literal notation differences in JS

Is there a difference between how JavaScript handles the following two declarations? JavaScript处理以下两个声明的方式之间有区别吗?

var foo = {
    foo : true,
    bar : 1
};

var foo2 = {
    "foo" : true,
    "bar" : 1
};

JavaScript seems to treat them the same. JavaScript似乎对它们相同。 If they really are the same then, is there a "correct" or preferred way to declare this? 如果它们确实相同,那么是否有“正确”或首选的方式来声明呢?

Either form is fine for "initializing" an object (aka. declaring an object literal). 两种形式都可以“初始化”对象(也就是声明对象文字)。

Property identifiers may be either names, numbers, or strings but they are all interpreted as strings: 属性标识符可以是名称,数字或字符串,但是它们都被解释为字符串:

var foo = {
  foo  : true,
  "bar": true,
  3    : true
};

See the ECMA-262 5th Edition Language Specification § 11.1.5 for more details. 有关更多详细信息, 请参见ECMA-262第5版语言规范§11.1.5

Note that the PropertyName construct might have changed in the 5th edition (as many things did) so browsers that do not support the most recent version of JavaScript might implement a different version of ECMAScript. 请注意, PropertyName构造在第5版中可能已更改(就像许多事情一样),因此不支持最新版本JavaScript的浏览器可能会实现不同版本的ECMAScript。

Note also that JSON defines objects as sets of string/value pairs and strings are enclosed by quotation-marks: 还要注意, JSON将对象定义为一组字符串/值对,并且字符串用引号引起来:

var fooJSON = '{"foo":true,"bar":true,"3":true}';

Your first sample is not json 您的第一个样本不是 json

{
    foo: true,
    bar: 1
}

在此处输入图片说明

So your second code ( jsonlint ) IS json. 因此,您的第二个代码( jsonlint )是json。

 {
    "foo": true,
    "bar": 1
}

Regarding your actual question , they are both the same. 关于您的实际问题,它们都是相同的。

Regarding the comment : 关于评论:

If they are the same, but if the first example is not json, but the second is json, what is the difference? 如果它们相同,但是如果第一个示例不是json,但是第二个示例是json,则有什么区别?

Let's say I have this string which should(but is not) represent json string representation : 假设我有一个应该(但不是)表示json字符串表示形式的字符串:

This string comes from the server : 此字符串来自服务器:

" {foo: true,bar: 1}"

Now I want to Parse it. 现在我要解析它。

Running 跑步

JSON.parse(" {foo: true,bar: 1}")

Will fail : 将失败 :

SyntaxError: Unexpected token f 语法错误:意外的令牌f

However : 但是:

JSON.parse("{\\"foo\\": true,\\"bar\\": 1}")

Will do just fine 会做的很好

Object {foo: true, bar: 1}

So here is a difference (one difference example) . 所以这是一个差异(一个差异示例)。

Speaking of how JS see/treats both objects ( Objects !!! , I didn't say json cuz the first one is not json) - they are the same. 说到JS如何查看/处理两个对象( Objects !!!,我没有说json cuz,第一个不是json)-它们是相同的。

PS , another helpful feature is that props are considered as strings even if you didnt use "myProp" : PS,另一个有用的功能是,即使您未使用"myProp" ,也可以将道具视为字符串:

example : 例如:

var a={myProp:1};  //notice no `"`
var b="myProp"; 
 a[b]=2; 
alert(a.myProp) //2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM