正确解析JavaScript八进制转义序列

fac*_*tus 6 javascript

根据ECMA规范,八进制转义序列定义为

OctalEscapeSequence ::  
    OctalDigit [lookahead ? DecimalDigit]  
    ZeroToThree OctalDigit [lookahead ? DecimalDigit]  
    FourToSeven OctalDigit  
    ZeroToThree OctalDigit OctalDigit  

ZeroToThree :: one of
    0 1 2 3

FourToSeven :: one of
    4 5 6 7
Run Code Online (Sandbox Code Playgroud)

根据这个规范,字符串"\379"不是八进制转义\37后跟9.我看对了吗?它不满足第一个规则,因为7是十进制数字.它不满足第二个,因为9是十进制数字.它不满足第三个,因为三个不是其中之一4 5 6 7.最后,它不满足第四个,因为9不是八进制数字.

那么当时的价值是"\379"什么?我尝试了JavaScript的翻译人员,他们将它解释为一个八进制转义\37之后9.这是口译员的错误吗?

UPDATE

我知道八进制转义序列在最新的ECMA规范中是可选的.

Mik*_*uel 2

The octal escape sequence is not part of the official spec implemented by modern browsers.

B.1 Additional Syntax

Past editions of ECMAScript have included additional syntax and semantics for specifying octal literals and octal escape sequences. These have been removed from this edition of ECMAScript. This non-normative annex presents uniform syntax and semantics for octal literals and octal escape sequences for compatibility with some older ECMAScript programs.

and it's explicitly disallowed in strict mode:

B.1.1 Numeric Literals

The syntax and semantics of 7.8.3 can be extended as follows except that this extension is not allowed for strict mode code


Given that, \379 is not an octal escape sequence since the negative lookahead of decimal digit bars both \3 and \37 from being treated as octal escape sequences.

This is then a syntax error since no other production matches it. Specifically,

CharacterEscapeSequence ::
  SingleEscapeCharacter
  NonEscapeCharacter
Run Code Online (Sandbox Code Playgroud)

(which is what causes "\-" to be equal to "-") does not apply because digits are not in SingleEscapeCharacter nor in NonEscapeCharacter.


Is it a bug in the interpreters?

Maybe not if it only happens in unstrict mode. Interpreters are allowed to define additional syntax per chapter 16:

An implementation may extend program syntax and regular expression pattern or flag syntax.

An interpreter author could probably make a case that they're a conforming implementation with this behavior, they just extend syntax to support octal in a different way than that suggested by section B.1.