What is the difference between object keys with qu

2018-12-31 04:37发布

Is there any difference between

obj = {'foo': 'bar'} 

and

obj = {foo: 'bar'}

I have noticed that you can't use - in the key when I don't use the quotes. But does it actually make a difference? If yes, which?

标签: javascript
6条回答
骚的不知所云
2楼-- · 2018-12-31 04:49

There are some situations where they are different. For example, if you are using jQuery, and you are making a list of parameters to pass when calling the jQuery $() command to create an element, quoted words are turned into parameters, and non-quoted words are turned into functions. For example, "size" will set the size attribute of the object, and size (no quotes), will call the size() function on the object. See jQuery(), near the bottom:

While the second argument is convenient, its flexibility can lead to unintended consequences (e.g. $( "<input>", {size: "4"} ) calling the .size() method instead of setting the size attribute). The previous code block could thus be written instead as:

查看更多
不流泪的眼
3楼-- · 2018-12-31 04:50

There is no difference here. Just a matter of style. One of the reasons for doing this is being able to use 'super' or 'class' as a key since those are reserved keywords.

Some people might be tempted to pass in a string with whitespace then call o['I can have whitespace'] But I would call that bad practice.

查看更多
零度萤火
4楼-- · 2018-12-31 04:57

No, the quotes do not make a difference (unless, as you noted, you want to use a key that’s not a valid JavaScript identifier).

As a side note, the JSON data exchange format does require double quotes around identifiers.

查看更多
临风纵饮
5楼-- · 2018-12-31 04:58

Differences:

  1. No quote: It is an object when there is no quote.

Access the object's member: object.member

  1. Has quote: It is an map when there is quote.

Access the map's member: object[member]

查看更多
冷夜・残月
6楼-- · 2018-12-31 04:59

No, not to javascript. However, some JSON parsers will fail when the quotes around the keys are not present.

查看更多
春风洒进眼中
7楼-- · 2018-12-31 05:06

From Unquoted property names / object keys in JavaScript, my write-up on the subject:

Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.

[…]

Bracket notation can safely be used for all property names.

[…]

Dot notation can only be used when the property name is a valid identifier name.

Note that reserved words are allowed to be used as unquoted property names in ES5. However, for backwards compatibility with ES3, I’d suggest quoting them anyway.

I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.

Screenshot

查看更多
登录 后发表回答