语法错误:后面缺少名字。 运算符

当点运算符 (.) 用于 属性访问权 的方式出现问题时,就会出现 JavaScript 异常 "后面缺少名字。 运算符"。

¥The JavaScript exception "missing name after . operator" occurs when there is a problem with how the dot operator (.) is used for property access.

信息

¥Message

SyntaxError: missing name after . operator (Firefox)
SyntaxError: Unexpected token '['. Expected a property name after '.'. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

点运算符 (.) 用于 属性访问权。你必须指定要访问的属性的名称。对于计算属性访问,你可能需要将属性访问从使用点更改为使用方括号。这些将允许你计算表达式。也许你打算改为串联?在这种情况下需要加号运算符 (+)。请参阅下面的示例。

¥The dot operator (.) is used for property access. You will have to specify the name of the property that you want to access. For computed property access, you might need to change your property access from using a dot to using square brackets. These will allow you to compute an expression. Maybe you intended to do concatenation instead? A plus operator (+) is needed in that case. Please see the examples below.

示例

¥Examples

属性使用权

¥Property access

JavaScript 中的 属性访问器 使用点 (.) 或方括号 ([]),但不能同时使用两者。方括号允许计算属性访问。

¥Property accessors in JavaScript use either the dot (.) or square brackets ([]), but not both. Square brackets allow computed property access.

js
const obj = { foo: { bar: "baz", bar2: "baz2" } };
const i = 2;

obj.[foo].[bar]
// SyntaxError: missing name after . operator

obj.foo."bar"+i;
// SyntaxError: missing name after . operator

要修复此代码,你需要像这样访问该对象:

¥To fix this code, you need to access the object like this:

js
obj.foo.bar; // "baz"
// or alternatively
obj["foo"]["bar"]; // "baz"

// computed properties require square brackets
obj.foo["bar" + i]; // "baz2"
// or as template literal
obj.foo[`bar${i}`]; // "baz2"

属性访问与串联

¥Property access vs. concatenation

如果你来自其他编程语言(例如 PHP),也很容易混淆点运算符 (.) 和串联运算符 (+)。

¥If you are coming from another programming language (like PHP), it is also easy to mix up the dot operator (.) and the concatenation operator (+).

js
console.log("Hello" . "world");

// SyntaxError: missing name after . operator

相反,你需要使用加号进行串联:

¥Instead you need to use a plus sign for concatenation:

js
console.log("Hello" + "World");

也可以看看

¥See also