[Vue] es6 deconstruction assignment - Assignment objects deconstruction

Deconstruction and an array of objects there is an important difference.

Elements of the array are arranged in order, the value of the variable is determined by its location

The properties of the object did not order, and variables must attribute of the same name, in order to get the correct value.

Basic Usage

  •  If deconstruction fails, the variable value is equal undefined. 
    let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
    foo // "aaa"
    bar // "bbb"
    
    let { baz } = { foo: 'aaa', bar: 'bbb' };
    baz // undefined

     

  • If the variable name and attribute name is inconsistent, it must be written as follows.
    let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
    baz // "aaa"
    foo // error: foo is not defined

    The above code, foois a matched pattern, bazis variable. Truly assignment is a variable baz, rather than the modefoo

Object deconstruction defaults

  • The default value of the entry into force of the conditions is that object's property value exactly equal undefined.
    var {x = 3} = {};
    x // 3
    
    var {x, y = 5} = {x: 1};
    x // 1
    y // 5
    
    var {x: y = 3} = {};
    y // 3
    
    var {x: y = 3} = {x: 5};
    y // 5
    
    var { message: msg = 'Something went wrong' } = {};
    msg // "Something went wrong"
    
    var {x = 3} = {x: undefined};
    x // 3
    
    var {x = 3} = {x: null};
    x // null
  • If you want a variable has been declared for the deconstruction of the assignment, be very careful.
    // error writing 
    the let X; 
    {X} = {X:. 1 };
     // SyntaxError: The above code written syntax error will be error, 
    // JavaScript engine as will {x}be understood as a code block, whereby a syntax error occurs.
    // braces will not only write the beginning of the line to avoid JavaScript interprets it as a block of code, in order to solve this problem.
    // correct wording of the let X; ({X} = {X:}. 1);
  • Among the deconstruction assignment mode allows the left side of the equal sign, do not place any variable name. Therefore, it is very strange to write an assignment expression.
    ({} = [true, false]);
    ({} = 'abc');
    ({} = []);

    Although the above expression is meaningless, but the syntax is legal, it can be performed.

  • Since the array is the special nature of the object, the object can be deconstructed attribute array
    let arr = [1, 2, 3];
    let {0 : first, [arr.length - 1] : last} = arr;
    first // 1
    last // 3

     

Guess you like

Origin www.cnblogs.com/websmile/p/11528527.html