例如,给定这个对象:
let foo = {foo:1};
let bar = {a:foo,b:foo};
我们可以将 bar
定义为单个表达式,将其写为:
let bar = (($0)=>({a:$0={foo:1},b:$0}))()
但是,给定这个对象:
let o = {a:'perfect'};
o.circle = o;
是否可以使用单个表达式重新创建 o
的结构?
这行不通:
(($0)=>($0={a:"perfect",circle:$0}))()
因为circle
是嵌套的,并且$0
已经定义了。
最佳答案
除非您想使用 getter 属性来解决这个问题,否则赋值是不可避免的。
有很多种方法可以做到这一点,甚至在单个表达式中也是如此:
let o = (o = {a:'perfect'}).circle = o;
但我建议重点关注清晰度并使用 IIFE:
const o = (function(){
const x = {a:'perfect'};
x.circle = x;
return x;
}());
// more like the first solution but without the mutable `o` variable:
const o = (x => x.circle = x)({a:'perfect'});
关于javascript - 如何用单个表达式定义递归对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45747598/