关于 JavaScript 键上引号的标准或最佳做法是什么?

What is the standard or best practice with regards to quotes on JavaScript keys?

我一直在研究 this 等几个问题,看看是否有关于是否在 JavaScript 或 JSX 或 TSX 中的键上加引号的标准实践/最佳实践。然而,我还没有找到任何东西,并且想知道(在建立一个关于不良做法的大型项目之前)哪个是最好的:

obj = {'foo': 'bar'}

obj = {foo: 'bar'}

或者更好的是,有没有我可以参考的文档?

查看 Airbnb JavaScript Style Guide。它有一套标准的指南和最佳实践。

  • 3.6 Only quote properties that are invalid identifiers. eslint: quote-props

Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.

// bad
const bad = {
  'foo': 3,
  'bar': 4,
  'data-blah': 5,
};

// good
const good = {
  foo: 3,
  bar: 4,
  'data-blah': 5,
};

ESLint 文档对此有一些意见:

In many cases, it doesn't matter if you choose to use an identifier instead of a string or vice-versa. Even so, you might decide to enforce a consistent style in your code.

There are, however, some occasions when you must use quotes:

  • If you are using an ECMAScript 3 JavaScript engine (such as IE8) and you want to use a keyword (such as if) as a property name. This restriction was removed in ECMAScript 5.
  • You want to use a non-identifier character in your property name, such as having a property with a space like "one two".

Another example where quotes do matter is when using numeric literals as property keys:

var object = { 1e2: 1, 100: 2 };

IMO 最好在需要时使用引号。

两者都有效,这取决于你想做什么,但我的大学老师确实告诉我们不要使用引号,以使其与字符串值有点不同,因此我们将整个 class 作为标准采用练习

obj = {foo: 'bar'}