【问题标题】:JavaScript object literal not working [duplicate]JavaScript对象文字不起作用[重复]
【发布时间】:2023-03-28 08:18:01
【问题描述】:

这是JavaScript object literals 中的错误,至少是解析器?

////////// a bug in JavaScript? //////////

// works:
const pointless = {
  "a b": 1,
  "c": 2
};

// works:
({
  "a b": 1,
  "c": 2
});

// fails when uncommented:
// {
//   "a b": 1,
//   "c": 2
// };

////////// what lead to the above //////////

// works:
class Thing {
  static get table() {
    return {
      'x': function () { console.log('You chose x!') },
      'y': function () { console.log('You chose y!') }
    };
  }
    
  static doAllTheThings(arg) {
    this.table[arg]();
  }
}

Thing.doAllTheThings('x');

// works:
function doAllTheThings(arg) {
  ({
    'x': function () { console.log('You chose x!') },
    'y': function () { console.log('You chose y!') }
  })[arg]();
}

doAllTheThings('y');

// fails when uncommented:
// function doAllTheThings(arg) {
//   {
//     'x': function () { console.log('You chose x!') },
//     'y': function () { console.log('You chose y!') }
//   }[arg]();
// }

// doAllTheThings('y');

现场演示:https://repl.it/repls/DeadlyFatherlyVertex

我偶然发现了这个,试图制作一个跳转表,而不是使用一个巨大的 switch 命令。将{} 包装在() 中是可行的,但恕我直言,这不是必需的。

这样做有什么原因吗?

【问题讨论】:

  • 如果{ 出现在语句的开头,则将其视为代码块的开头,而不是对象字面量。
  • 嘿@Pointy,这个被骗了吗?我的语法重复列表中没有它。
  • 并且 - 当它首先看到 ( 时,它只是验证 () 之间的内容是一个有效的 Javascript 表达式。所以({...}) 并没有按照你的想法去做。
  • 那里肯定有骗子;我可以试试,但我的 SO 搜索运气很差。
  • 哇你们真快!从我要求被标记为重复的时间起 5 分钟 :-)

标签: javascript parsing object literals


【解决方案1】:

当您使用() 包围{} 时,您正在创建一个表达式,这是对象被评估的方式。

但是,您也可以通过简单地使用 {} 在 JavaScript 中创建一个空范围(仍然与周围范围相关联),结果,您认为是对象的内部实际上被解释为代码行, "a b" : 1, 失败,这是无效的代码行。

{
    console.log(1);
}

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2012-09-22
    • 1970-01-01
    相关资源
    最近更新 更多