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

另見