Parsing error: Unexpected token, expected "," AND SyntaxError: Unexpected token '['

Parsing error: Unexpected token, expected "," AND SyntaxError: Unexpected token '['

app.js

let ids = [1, 2, 3];

let obj = {};

for (let i in ids) {
  obj = { ...obj, ids[i]: "" };   
}

console.log(obj);

执行上述代码时,出现以下错误。

Parsing error: Unexpected token, expected ","

  4 |
  5 | for (let i in ids) {
> 6 |   obj = { ...obj, ids[i]: "" };  
    |                      ^
  7 | }
  8 |
  9 | console.log(obj);eslint

我在 VS Code 中将鼠标悬停在行 obj = { ...obj, ids[i]: "" }; 上方时出现此错误。

当我 运行 使用节点的代码时,即 node app.js。我的终端出现以下错误:

obj = { ...obj, ids[i]: "" };  
                     ^

SyntaxError: Unexpected token '['
    at wrapSafe (internal/modules/cjs/loader.js:988:16)
    at Module._compile (internal/modules/cjs/loader.js:1036:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47

我做错了什么?我希望 obj 最后的值是 {1 : "", 2 : "", 3: ""}

使用 [ids[i]] 而不是 ids[i]

let ids = [1, 2, 3];

let obj = {};

for (let i in ids) {
  obj = { ...obj, [ids[i]]: "" };
}

console.log(obj);

有几种解决方案。

  1. 用括号括起来:
for (let i in ids) {
  obj = { ...obj, [ids[i]]: "" }; // Brackets make it act as a key name instead of something else
}
  1. 简单易行的方法:
for (let i in ids) {
  obj[ids[i]] = ""; // This adds a value
}

is[i]key 应该在运行时解析,所以你应该把它设为 computed property names

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties already. - MDN

let ids = [1, 2, 3];

let obj = {};
for (let i in ids) {
  obj = { ...obj, [ids[i]]: "" };
}

console.log(obj);

如果你想动态设置 "" 到每个 id 作为对象中的键,我建议你这样做:

let obj = {} let ids = [1,2,3]

ids.forEach((id) => {
   obj[id] = '';
});

对象将是 { '1': '', '2': '', '3': ''};