javascript 中有多少文字?

How many literals are there in javascript?

我正在做一些涉及正则表达式的项目,突然遇到一个 regex literal,看起来像这样:

/ab+c/g

我知道在编程语言中有一些固定的可能文字列表,例如 C 语言 integerfloat

然后我搜索了 javascript 支持的文字列表,但没有找到满意的答案。

我尝试了节点提示并得到了以下有趣的结果:

> typeof /ab+c/g
'object'
> str = 'xyz'
'xyz'
> typeof `abc ${str}`
'string'
> typeof function f(x, y) {
... return x + y;
... }
'function'
> typeof {
... 'a': 'b'
... }
'object'

这证明

尽管最后一个没问题并且在很多地方都有定义,但正则表达式文字仍然是 object literal.

对我来说没有意义

写在什么地方?如何找出 javascript 中可能的文字列表?

看看 the spec 的附录 A,你会发现 StringLiteral 等的定义。顺便说一句,规范使用 FunctionExpression,而不是 FunctionLiteral.

同样相关的是 11.8 Literals。下面是

  • NullLiteral ::== null
  • 布尔文字 ::== true | false
  • 数字文字
  • 正则表达式文字
  • StringLiteral
  • TemplateLiteral 个组件。

值得注意的是,undefined 不是文字。

如该部分所述,"literal" 指的是缩写语法,与任何 object/primitive 区别无关。

在文本的其他地方(第 12 章 PrimaryExpression)你会看到像 ObjectLiteralArrayLiteral 但那些也被称为 {Object,Array}Initializers.

您可能会避免过度考虑 typeof 结果。虽然偶尔对于确定变量持有什么样的值很有用,但它与对象 type 在 C 或 OOP 语言中所知道的意义上并不完全相同。

观察:

typeof (()=>{})
> "function"
(()=>{}) instanceof Object
> true

还有:

typeof ""
> "string"
typeof new String("")
> "object"
"" instanceof String
> false

为了回答你的主要问题,有以下文字:

  • ()=>{} lambda 字面量
    • typeof ()=>{} == "function"
  • function() {} 函数字面量
    • typeof function() {} == "function"
  • "" 字符串文字
    • typeof "" == "string"
  • `` 字符串模板文字
    • typeof `` == "string"
  • 42 数字文字
    • typeof 42 == "number"
  • /x/ RegExp 文字
    • typeof /x/ == "object"
  • [] 数组文字
    • typeof [] == "object"
  • false 布尔文字
    • typeof false == "boolean"
  • null 空对象的文字,注意
    • typeof null == "object"
  • {} 和对象字面量
    • typeof {} == "object"

在所有这些中,只有字符串文字和数字文字具有 value instanceof Object == false。其余的都是对象实例。

typeofinstanceof 中的注意事项在编写可能接收各种类型的代码时很重要。一般typeof的逻辑是:

  • 它是原始字符串吗(不是 new String)? - return "string"
  • 这是原始数字吗? - return "number"
  • 它是原始布尔值吗? - return "boolean"
  • 是不是undefined(注意null不是undefined!) - return "undefined"
  • 是函数吗? - return "function"
  • 否则return"object"