简体   繁体   English

用值破坏声明错误

[英]Destructuring declaration bug with the value

I can not understand why after destructuring assignment, items prop does not equal Gorilla . 我不明白为什么解构赋值后, items道具不等于Gorilla

It will be used after deleting the main prop items: "Piggi" in the origin object options. 将在删除主要道具items: "Piggi"原始对象选项中的items: "Piggi"后使用。 I do not understand why... 我不理解为什么...

  '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" 

In the destructuring declaration with initialization here: 在具有初始化的销毁结构声明中:

let { items:w = "Gorilla" } = options;

the syntax means to declare a variable called "w", whose value should be initialized to the value of the property called "items" in the object referenced by "options", or if there is no such property then to the string "Gorilla". 该语法意味着声明一个名为“ w”的变量,该变量的值应初始化为“ options”所引用的对象中名为“ items”的属性的值,或者如果没有这样的属性,则应初始化为字符串“ Gorilla” 。

In your case, then, the variable "w" is initialized to the value of the "items" property in the original object. 然后,在您的情况下,变量“ w”被初始化为原始对象中“ items”属性的值。

If you don't want to take the value from the source object, then don't: 如果您不想从源对象获取值,请不要:

let w = "Gorilla";

When you analyze the code, you get three techniques working here: 分析代码时,您可以在这里使用三种技术:

  1. short hand properties 短手性能

     { foo, bar } 

    for 对于

     { foo: foo, bar: bar} 
  2. default values 默认值

     { foo = 42 } 

    which is 这是

     { foo: foo = 42 } 
  3. change of the target in the Object Property Assignment Pattern [You Don't Know JS: ES6 & Beyond, Chapter 2: Syntax] : 对象属性分配模式中更改目标[您不知道JS:ES6及更高版本,第2章:语法]

    The syntactic pattern here is source: target (or value: variable-alias ). 这里的语法模式是source: target (或value: variable-alias )。

     { foo: bar } 

The synthesis is a new target w for the old property items with a default value of 'Gorilla' . 综合是旧属性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);

Solution - The problem is , we are overwriting the global object. 解决方案 -问题是,我们正在覆盖全局对象。 it is why you have titile as Menu but option object does not have titile property. 这就是为什么您拥有Title作为Menu但选项对象没有titile属性的原因。 So, when you assign global object with option, it still has items as "piggi" plus you cannot assign object like this, you have to reassign each property in javascript. 因此,当您为全局对象分配选项时,它仍然具有“ piggi”项,并且您无法像这样分配对象,因此必须在javascript中重新分配每个属性。 i hope you got your answer. 我希望你能得到答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM