>> var x = {"active": "yes"} >>> x.active "yes" >>> var x = {active-6ren">
gpt4 book ai didi

javascript - {active : "yes"} and {"active": "yes"}? 有什么区别

转载 作者:可可西里 更新时间:2023-11-01 02:28:35 27 4
gpt4 key购买 nike

我使用 FireBug 测试了这两种情况,结果看起来非常相似:

>>> var x = {"active": "yes"}
>>> x.active
"yes"
>>> var x = {active: "yes"}
>>> x.active
"yes"

但我很确定这两者之间存在一些差异,甚至可能是与性能相关的差异。底线 - 我想知道 {active: "yes"} 和 {"active": "yes"} 之间是否有区别。

最佳答案

两者都有效。但是,有些关键字不能使用,例如 delete,因此为了避免将它们用引号引起来,这样它们就不会被 ECMAScript 解析器逐字处理,而是被明确指定为字符串。

另外,JSON spec要求键周围有引号:

A string begins and ends with
quotation marks

因此 {key:'value'} 不是有效的 JSON,而是有效的 JS,而 {"key":"value"} 是有效的 JS 和 JSON。

关键字和无效/不明确键的示例:

>>> ({delete:1})
SyntaxError: Unexpected token delete
>>> ({'delete':1})
Object

另一个例子:

>>> ({first-name:'john'})
SyntaxError: Unexpected token -
>>> ({'first-name':'john'})
Object
>>> ({'first-name':'john'})['first-name']
"john"

关于javascript - {active : "yes"} and {"active": "yes"}? 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3998798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com