具有默认值分配的ES6对象解构 [英] ES6 object destructuring with a default value assignment
问题描述
考虑以下代码:
const log = ({a,b=a}) => console.log(a,b);
log({a:'a'})
为变量 b
分配了值 a
.将其编译到es5时确实可以使用,但是我不确定这是否是有效的es6语法.
The variable b
is assigned the value a
. This does work when transpiling it to es5, but I am not entirely sure if this is valid es6 syntax.
我可以在变形对象中进行这种默认值分配吗?
Am I allowed to do this kind of default value assignment in a destructured object?
推荐答案
const log = ({a,b=a}) => console.log(a,b);
log('a')
在语法上有效,但在语义上无效,因为您正试图解构一个字符串原语,该字符串原语被装箱到临时的 String
对象包装器中,并试图同时获取 a
和 b
属性,它们始终是 undefined
,因为包装对象是临时的,并且仅出于操作触发装箱本身的目的而创建.
is syntactically valid but semantically invalid, since you are trying to destructure a string primitive, which gets boxed into a temporary String
object wrapper, and tries to get both a
and b
properties, which are always undefined
since the wrapper object is temporary and only created for the sake of the operation triggering the boxing itself.
因此,您在调用它时具有 undefined,undefined
.
Thus you have undefined, undefined
when you call it.
具有默认值的解构操作在语义上可能是有效的在您的情况下,像这样的通话:
The destructuring operation with defaults could be semantically valid in your case with a call like this:
const log = ({a,b=a}) => console.log(a,b);
log({a: 'a'}) // a,a
UPD:
但是请注意,提供默认值的顺序很重要,因此这不会工作
But beware that order of supplying default value matters, so this won't work
const log = ({a=b,b}) => console.log(a,b);
log({a: 'a'}) // error
因为解构发生在参数对象初始化之后,并且从左到右进行求值,所以 b
尚未解构,并且在我们尝试对 a
进行解构时知道如果未定义 a
.
because destructuring happens after argument object initialization and is evaluated from left to right, thus b
is not yet destructured and known by the time we destructure a
to try to reference it in case a
is undefined.
这篇关于具有默认值分配的ES6对象解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!