为什么当点 (`.`) 运算符前面有空格时,只有对数字文字执行属性访问才是有效的语法?
以下 JavaScript 代码:
console.log(2 .toString());
输出“2”。
(注意:“2”和“.x”之间的空格是有意的)
简单的问题:为什么?特别是当出现以下yield语法错误时:
console.log(2.toString());
console.log(2. toString());
The following JavaScript code:
console.log(2 .toString());
Outputs “2”.
(Note: The space between the '2' and '.x' is intended)
Simple question: Why? Especially when the following yield syntax errors:
console.log(2.toString());
console.log(2. toString());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.
是一个运算符。2
是一个数字。x
是(被视为)属性名称。浮点数值常量不得嵌入空格。因此,
2 .x
是一个表达式,要求将常量2
提升为 Number 对象,然后检查名为“x”的属性。当然,没有,因此该值是未定义
。更明确地获得相同的效果
您可以使用有点相似的 Note
:在这种情况下,它不是一个数字常量,而是一个字符串常量。它不那么奇怪,因为不涉及语法上有趣的事情,但除此之外,解释器在评估时会做类似的事情。首先将字符串常量转换为 String 对象,然后获取“x”属性。
编辑 - 澄清一下,
2.x
是一个错误,因为它被解析为数字常量(“2.”)后跟标识符“x”,这就是语法错误;像这样没有中间运算符的两个值彼此相邻放置不会在语言中形成任何类型的构造。The
.
is an operator. The2
is a number. Thex
is (treated as) a property name.A floating-point numeric constant must not have embedded spaces. Thus,
2 .x
is an expression calling for the constant2
to be promoted to a Number object, and then the property called "x" is examined. There isn't one, of course, so the value isundefined
.You can get the same effect a little more explicitly with
Note that
is somewhat similar: in that case, it's not a numeric constant, it's a string constant. It's less peculiar because there's no syntactic funny business involved, but otherwise the interpreter does similar things when evaluating. The string constant is first converted to a String object, and then the "x" property is fetched.
edit — to clarify a little,
2.x
is an error because it's parsed as a numeric constant ("2.") followed by the identifier "x", and that's a syntax error; two values placed next to each other like that with no intervening operator do not form any sort of construct in the language.