简体   繁体   中英

Destructuring declaration bug with the value

I can not understand why after destructuring assignment, items prop does not equal Gorilla .

It will be used after deleting the main prop items: "Piggi" in the origin object options. 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".

In your case, then, the variable "w" is initialized to the value of the "items" property in the original object.

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] :

    The syntactic pattern here is source: target (or value: variable-alias ).

     { foo: bar } 

The synthesis is a new target w for the old property items with a default value of '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. 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. i hope you got your answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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