anjianshi
2022-03-31 11:28:07 +08:00
这种“骚操作”,既不简洁,也不容易读。且和 TypeScript 没有关系,就是普通 JavaScript 代码。
试试下面的?
```
// 原版本
var Cute;
(function (Cute) {
Cute[(Cute["Red"] = 2)] = "Red";
Cute[(Cute["Blue"] = 3)] = "Blue";
Cute[(Cute["Yellow"] = 4)] = "Yellow";
})(Cute || (Cute = {}));
var cc = Cute.Blue;
console.log('A', Cute, cc);
// 改良版
var Cute2 = [['Red', 2], ['Blue', 3], ['Yellow', 4]].reduce(function (o, pair) {
return {
...o,
[pair[0]]: pair[1],
[pair[1]]: pair[0]
}
}, {})
var cc2 = Cute2.Blue;
console.log('B', Cute2, cc2);
// 改良精简版
var Cute3 = [['Red', 2], ['Blue', 3], ['Yellow', 4]].reduce((o, [k, v]) => ({ ...o, [k]: v, [v]: k }), {})
var cc3 = Cute3.Blue;
console.log('C', Cute3, cc3);
```