简体   繁体   English

单引号参数与无引号参数?

[英]Single Quote Params vs No Quote Params?

This is something that's been mind boggling to me for a while, some times I see people writing javascript objects like so with single quote params: 这是我一直困扰着我的事情,有时我看到人们用单引号参数像这样编写JavaScript对象:

{
    'name': 'Teddy',
    'last': 'Monster'
}

But then I also see the more common, no quote params: 但是随后我也看到了更常见的无引号参数:

{
    name: 'Teddy',
    last: 'Monster'
}

Is there a reason one would use single quote params? 是否有理由使用单引号参数? Is it faster to parse? 解析速度更快吗?

From what I can see, there is no speed difference, rather just cluttering the file with unnecessary quotes and increasing file size. 据我所知,没有速度差异,只是用不必要的引号将文件弄乱了,并增加了文件的大小。

I'll change my mind if I can get a straight answer :) 如果我能得到一个直接的答案,我会改变主意:)

You can't define this hash: 您无法定义此哈希:

{
   function: 'foo'
}

But you can define 但是你可以定义

{
   'function': 'foo'
}

Personally, I use the former way, if there's no reserved keywords as keys (as to not clutter the code, like you've pointed out). 就个人而言,如果没有保留的关键字作为键,则我使用前一种方法(如您所指出的那样,不要使代码混乱)。

从技术上讲,根据JSON规范 ,第二种形式无效,但在所有主流Javascript引擎中都可以正常使用。

A quick Google search finds this answer on this very website . 快速的Google搜索可以在这个网站上找到答案。 Essentially there's no functional difference if you're talking about object literals, but the properties can't be reserved words like "class" or "namespace". 如果您在谈论对象文字,则本质上没有功能上的区别,但是属性不能是诸如“类”或“命名空间”之类的保留字。 Wrapping the property in quotation marks allows those words to be used 将属性包装在引号中可以使用这些单词

Single quoting allow you to use any valid string , including reserved keywords or characters than would be invalid in an identifier 单引号允许您使用任何有效的字符串 ,包括比标识符中无效的保留关键字或字符

Example: 例:

{
  'return' : 'ok',
  'with-hyphen' : '123'
}

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

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