5

JavaScript 处理以下两个声明的方式有区别吗?

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

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

JavaScript 似乎对它们一视同仁。如果它们确实相同,那么是否有“正确”或首选的方式来声明这一点?

4

2 回答 2

3

任何一种形式都适用于“初始化”一个对象(也就是声明一个对象字面量)。

属性标识符可以是名称、数字或字符串,但它们都被解释为字符串:

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

有关更多详细信息,请参阅 ECMA-262 第 5 版语言规范 § 11.1.5

请注意,PropertyName结构可能在第 5 版中发生了变化(正如许多事情所做的那样),因此不支持最新版本 JavaScript 的浏览器可能会实现不同版本的 ECMAScript。

另请注意,JSON 将对象定义为字符串/值对的集合,并且字符串用引号括起来:

var fooJSON = '{"foo":true,"bar":true,"3":true}';
于 2013-10-10T13:58:11.497 回答
2

Your first sample is not json

{
    foo: true,
    bar: 1
}

enter image description here

So your second code (jsonlint) IS 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?

Let's say I have this string which should(but is not) represent json string representation :

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

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.

PS , another helpful feature is that props are considered as strings even if you didnt use "myProp" :

example :

var a={myProp:1};  //notice no `"`
var b="myProp"; 
 a[b]=2; 
alert(a.myProp) //2
于 2013-10-10T13:50:36.467 回答