[英]Destructuring declaration bug with the value
我不明白为什么解构赋值后, items
道具不等于Gorilla
。
将在删除主要道具items: "Piggi"
原始对象选项中的items: "Piggi"
后使用。 我不理解为什么...
'use strict'; let options = { size: 100, items: "Piggi" } let { title="Menu", items:w="Gorilla", size } = options; let a = title; let b = w; console.log(a + " - " + b); // must be "Menu - Gorilla"
在具有初始化的销毁结构声明中:
let { items:w = "Gorilla" } = options;
该语法意味着声明一个名为“ w”的变量,该变量的值应初始化为“ options”所引用的对象中名为“ items”的属性的值,或者如果没有这样的属性,则应初始化为字符串“ Gorilla” 。
然后,在您的情况下,变量“ w”被初始化为原始对象中“ items”属性的值。
如果您不想从源对象获取值,请不要:
let w = "Gorilla";
分析代码时,您可以在这里使用三种技术:
{ foo, bar }
对于
{ foo: foo, bar: bar}
{ foo = 42 }
这是
{ foo: foo = 42 }
在对象属性分配模式中更改目标[您不知道JS:ES6及更高版本,第2章:语法] :
这里的语法模式是
source: target
(或value: variable-alias
)。
{ foo: bar }
综合是旧属性items
的新目标w
,默认值为'Gorilla'
。
let options = {
size: 100,
items: "Piggi"
}
let { title="Menu", items:w="Gorilla", size } = options;
let a = title;
let b = w;
console.log(a + " - " + b);
解决方案 -问题是,我们正在覆盖全局对象。 这就是为什么您拥有Title作为Menu但选项对象没有titile属性的原因。 因此,当您为全局对象分配选项时,它仍然具有“ piggi”项,并且您无法像这样分配对象,因此必须在javascript中重新分配每个属性。 我希望你能得到答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.