是否应在Javascript Objects关键字中加引号? [英] Should Javascript Objects keys be quoted in?

查看:71
本文介绍了是否应在Javascript Objects关键字中加引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可能有与此相关的一些问题,但我没有发现与javascript严格相关的任何内容.

I know there are some questions that may refer to this, but I didn't find anything related to javascript strictly.

例如: JSON规范-密钥是否必须被包围带有引号?

但是我的问题是:编写 Javascript 对象时,我们应该使用引号吗?

But my question is: should we use quotes when we write a Javascript Object?

我认为写没有引号而且可读性也更好,但是可以吗?

I think it is more elegant to write is without quotes and also more readable, but is it OK?

例如,当我使用它作为参数传递时:

For example when I use it to pass as an argument:

myFunction({
    "key": "value",
    "otherKey": 10
});


myFunction({
    key: "value",
    otherKey: 10
});

据我所读,第二个在每个浏览器中都可以使用,除非它是一个禁止字(for,if等),所以这不是问题.

Also as I read, the second one works in every browser, unless it is a forbidden word (for, if, etc), so this wouldn't be a problem.

我认为第二个看起来更好,但我也认为这可能不是一个好习惯.

I think the second one looks better, but I also think it may not be a good practice..

我做了多年的练习,现在我开始觉得我错了,但是使用引号我感觉不太好. 我该怎么办?

I did this practice for years and now I am starting to think that I was wrong but I don't feel it good using quotes.. What should I do?

推荐答案

简短答案:JavaScript对象键不需要用引号引起来.

因为:

JSON和JavaScript中的对象文字语法虽然有密切的联系,但却是不同的东西.

JSON and the object literal syntax in JavaScript are different things, although they are closely related.

JSON必须在服务器和客户端之间作为字符串传输.因此,所有值都需要包装在""中,以便可以在到达它们时对其进行标记,拆分和重新构造为对象.

JSON has to be transmitted as a string between the server and the client. Because of this, all the values need to be wrapped in "" so they can be tokenized, split, and reconstructed back into objects when they arrive.

JavaScript文字语法不必经过此传输,因此引号不是必需的.约定规定,除非键有空格或特殊的保留字,否则不要使用引号.

The javascript literal syntax does not have to go through this transfer, and so the quotes are not necessary. Convention dictates that you do not use quotes unless the key has a space or is a special reserved word.

这篇关于是否应在Javascript Objects关键字中加引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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