简体   繁体   English

使用点符号和空格访问对象键

[英]Accessing object key with dot notation and space

I came across the following: 我遇到以下问题:

var object = {};
object.name = 'ABC';
console.log(object.     name); // this is still valid

Notice the space after object. 注意object.后的空格object.

Why is this valid? 为什么这样有效? Is there any ECMA specification for this? 是否有任何ECMA规范?

Same is true for all the inherited properties for different data types. 对于不同数据类型的所有继承属性也是如此。

I've tested this on a node terminal. 我已经在节点终端上对此进行了测试。

Thanks! 谢谢!

Why is this valid? 为什么这样有效?

Because whitespace is largely (though not entirely) irrelevant in the JavaScript syntax. 因为空格在JavaScript语法中很大程度上 (尽管不是全部)无关紧要。 You can safely insert any whitespace other than a line break between two tokens (and in most, but not all cases, you can insert line breaks as well; the "most" is due to ASI ). 您可以安全地在两个标记之间插入一个除换行符以外的空格(并且在大多数(但不是全部)情况下,您也可以插入换行符;“大多数”是由于ASI引起的)。 You can't insert spaces within tokens (because it breaks them up into two tokens), but you can between tokens. 您不能令牌中插入空格(因为它将空格分成两个令牌),但是您可以令牌之间插入空格。

As Federico klez Culloca points out ( link ), . 随着费德里科求职信Culloca指出( 链接. is an operator, just like + or * . 是运算符,就像+* The fact we generally don't put spaces around it, but do put spaces around them, is simply convention. 通常,我们通常不会在其周围放置空格,而是在其周围放置空格,这只是惯例。

These are all valid: 这些都是有效的:

console.log(object.name);
console.log(
    object.name
);
console.log(
    object . name
);
console.log(
    object
    .
    name
);

Is there any ECMA specification for this? 是否有任何ECMA规范?

Of course, the specification itself . 当然, 规范本身 Specifically here and here . 具体在这里这里 From that last link: 从最后一个链接:

Input elements other than white space and comments form the terminal symbols for the syntactic grammar for ECMAScript and are called ECMAScript tokens. 除空格和注释之外的其他输入元素构成ECMAScript语法的终端符号,称为ECMAScript标记。 These tokens are the reserved words, identifiers, literals, and punctuators of the ECMAScript language. 这些标记是ECMAScript语言的保留字,标识符,文字和标点符号。 Moreover, line terminators, although not considered to be tokens, also become part of the stream of input elements and guide the process of automatic semicolon insertion (11.9). 此外,行终止符尽管不被视为标记,但也成为输入元素流的一部分,并指导自动分号插入的过程(11.9)。 Simple white space and single-line comments are discarded and do not appear in the stream of input elements for the syntactic grammar. 简单的空格和单行注释将被丢弃,并且不会出现在语法语法的输入元素流中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM