Destructuring declaration bug with the value

2019-06-06 18:26发布

问题:

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"

回答1:

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


回答2:

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



回答3:

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.