Home  >  Article  >  Web Front-end  >  Detailed explanation of destructuring assignment in ES6

Detailed explanation of destructuring assignment in ES6

php中世界最好的语言
php中世界最好的语言Original
2018-05-19 15:40:481819browse

This time I will bring you a detailed explanation of the destructuring assignment of ES6. What are the precautions for using the destructuring assignment of ES6?The following is a practical case, let's take a look.

@1 Destructuring assignment of array;

let [a,b,c]=[1,2,3];
console.log(a,b,c)            //1 2 3
----------------------------------------------------------------
let [a=true]=[];
console.log(a)                //a=true;
----------------------------------------------------------------
let[a=true]=[undefined];
let[b=true]=[null]
console.log(a,b)             //a=true,b=null

In fact, it is very simple to understand the difference between undefined and null: although undefined==null;

, it is still distinguishable. Please refer to the Rhinoceros book Say null is an empty

ObjectPointer

typeof null  ==>object;而undefined可以认为在下面两种情况会出现;

1. Access an item that does not exist in the array;

2.Undefined variable var method;

So: the following two are equivalent;

let[a=true]=[undefined];
let[a=true]=[ ];

It’s not difficult to understand why;

@2 Destructuring assignment of objects;

Unlike arrays, destructuring assignment of objects is According to the key instead of the index;


let {foo,bar}={bar:"liuhf",foo:true};    //跟键的顺序没有关系;

 @3

Destructuring assignment of string;

const [a,b,c,d,e,f]="liuhee";
console.log(a,b,c,d,e,f);        // l i u h e e

Regardless of which kind of destructuring assignment, the left and right must correspond;

b59db7961ac00d8b96e1053e244a24fd
let json = {
        a: '对',
        b: '象'
    }
    //对象的函数解构;
function fun({ a, b = 'jspang' }) {
    console.log(a, b);
}
fun(json);
//数组的函数解构;
let arr = ["liu", "hai"]
function fun1([a, b]) {
    console.log(a, b);
}
fun1(arr);
console.log("------------");
//或者;
function fun2(a, b) {
    console.log(a, b);
}
fun2(...arr);
Believe it or not After reading the case in this article, you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Related reading:

Entry, output, module analysis of webpack3.x

##Vue2 tab switching method


Basic JavaScript knowledge summary (11) Object, packaging class

The above is the detailed content of Detailed explanation of destructuring assignment in ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn