【发布时间】: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