语法错误:八进制转义序列不能用于未标记的模板文字或严格模式代码

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

¥The JavaScript exception "octal escape sequences can't be used in untagged template literals or in strict mode code" occurs when octal escape sequences are used in strict mode string literals or untagged template literals.

信息

¥Message

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)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

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

¥The string escape sequence of the form \ followed by any number of digits, except a single 0, is deprecated. If you want to represent a character by its code point value, you should use the \x or \u escape sequence instead, such as \x01 or \u0001 instead of \1.

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

¥Untagged template literals are never allowed to contain octal escape sequences, whether in strict mode or not. However, tagged template literals can contain any form of escape sequence, and will cause the template array received by the tag function to contain undefined.

示例

¥Examples

八进制转义序列

¥Octal escape sequences

js
"use strict";

"\251";

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

有效的八进制数

¥Valid octal numbers

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

¥For octal escape sequences, you can use hexadecimal escape sequences instead:

js
"\xA9";

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

¥If you want to represent some source text literally without interpreting any escape sequence, use String.raw:

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

也可以看看

¥See also