【问题标题】:Why is there an unexpected token error when creating object? [duplicate]为什么创建对象时会出现意外的令牌错误? [复制]
【发布时间】:2017-05-28 15:11:04
【问题描述】:

我的场景是我正在尝试将标头添加到节点请求对象。但我只是想创建 headers 数组。

let headers = [];
let options = {
  url: this.baseUrl + appconst.route.postMessage
};

if (token) {
  console.log(appconst.headers.authToken); // no problem here
  let authTokenHeader = { appconst.headers.authToken: token.toBase64() }; // throws
  headers.push(authTokenHeader);
}

if (msg) {
  headers.push({ 'content-type': 'application/json' });
  options.body = JSON.stringify(msg);
}

“投掷”线正在给予......

  let authTokenHeader = { appconst.headers.authToken: token.toBase64() };
                                  ^
  SyntaxError: Unexpected token .

你能帮我理解这里发生了什么吗?我很困惑,因为定义了“const.headers.authToken”并且它上面的行工作正常。是的,我对 JavaScript 很陌生。

【问题讨论】:

  • 你不应该使用const作为变量名。
  • 如果你真的想使用const.headers.authToken作为你的对象的键名,你需要将它包裹在引号之间:"const.headers.authToken"
  • 对不起。它在实际代码中不是 const 。我只是将其更改为混淆问题,但没有意识到这会引入另一个错误。我的错。我会更新问题。
  • 是的,这是@CBroe 发布的内容的副本。我通过使用 EMAScript 2015 计算属性名称表示法将 appconst.headers.authToken 括起来更正了我的代码:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。

标签: javascript arrays node.js node-request


【解决方案1】:

const - 保留关键字。 只需根据您的需要选择另一个即可。

更新:

就我们使用appconst 而不是const 而言,还有另一个问题:您尝试分配嵌套属性。 有两种解决方法。首先你像这样创建对象字面量:

let authTokenHeader = { 
  appconst: {
    headers: {
      authToken: token.toBase64() 
    }
  }
};

另一种是像这样创建嵌套属性:

let authTokenHeader = {};

然后你分配属性:

authTokenHeader.appconst = {
  headers: {
    authToken: token.toBase64() 
  }
};

有一次我看到了另一种定义属性的奇怪方式,但只要我们都希望我们的代码可读 - 让我们保持原样。

【讨论】:

  • 大声当当。问题对我来说失败了。它实际上不是代码中的 const 。我将其更改为混淆专有名称的问题。我会解决这个问题。
  • @RichAmberale 我已经更新了我的答案。
猜你喜欢
  • 2019-01-02
  • 2020-05-22
  • 2018-01-06
  • 2013-03-29
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
相关资源
最近更新 更多