SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code

当在严格模式字符串字面量或未标记的模板字面量中使用八进制转义序列时,会发生 JavaScript 异常 "八进制转义序列不能用于未标记的模板字面量或严格模式代码"。

消息

SyntaxError: Octal escape sequences are not allowed in strict mode. (V8-based)
SyntaxError: \8 and \9 are not allowed in strict mode. (V8-based)
SyntaxError: Octal escape sequences are not allowed in template strings. (V8-based)
SyntaxError: \8 and \9 are not allowed in template strings. (V8-based)
SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code (Firefox)
SyntaxError: the escapes \8 and \9 can't be used in untagged template literals or in strict mode code (Firefox)
SyntaxError: The only valid numeric escape in strict mode is '\0' (Safari)

错误类型

SyntaxError

哪里出错了?

形式为 \ 后跟任意数字(除了单个 0)的字符串转义序列已被弃用。如果你想用其代码点值表示一个字符,你应该使用 \x\u 转义序列,例如 \x01\u0001 而不是 \1

未标记的模板字面量永远不允许包含八进制转义序列,无论是否在严格模式下。但是,标记的模板字面量可以包含任何形式的转义序列,并且会导致标签函数接收到的模板数组包含 undefined

示例

八进制转义序列

js
"use strict";

"\251";

// SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code

有效的八进制数字

对于八进制转义序列,你可以使用十六进制转义序列代替

js
"\xA9";

如果你想按字面意思表示某些源代码文本而不解释任何转义序列,请使用 String.raw

js
String.raw`\251`; // A string containing four characters

另见