ES6—Deconstruction

ES6 allows extracting values ​​from arrays and objects and assigning values ​​to variables according to a certain pattern. This is called deconstruction. The essence of deconstruction belongs to "pattern matching". As long as the patterns on both sides of the equal sign are the same, the variables on the left will be assigned corresponding value. If the deconstruction is unsuccessful, the value of the variable is equal to undefined.

1. Array destructuring

// 1.完全解构
let [a,b,c,d,e]=[1,2,3,4];
console.log(a,b,c,d,e);// 1 2 3 4 undefined

let [a,b,c,d,e]=[1,2,3,[4,5],6];
console.log(a,b,c,d,e);// 1 2 3 [ 4, 5 ] 6

// 2.不完全解构
let [a,b,c,[d],e]=[1,2,3,[4,5,6],7];// d=4
console.log(a,b,c,d,e);// 1 2 3 4 7

// 3.默认值解构 
// 默认值生效条件:当右侧匹配严格模式为undefiend
let [a=1,b=2,c=3]=[4,5,6];
console.log(a,b,c);// 4 5 6
let [a=1,b=2,c=3]=[4]
console.log(a,b,c); // 4 2 3
let [a=1,b=2,c=3]=[]
console.log(a,b,c); // 1 2 3

// 默认值也可以是一个函数
let test=()=>{
    console.log('我是一个箭头函数');
    return 1
}
let [x=test()] = [] 
console.log(x);// 1
let [x=test()] = [2] 
console.log(x);// 2

// 4.集合解构 拓展运算符
let [a,...b]=[1,2,3,4];
console.log(a,b);// 1 [ 2, 3, 4, 5 ]

1.1...Expansion operator

Use the spread operator to destructure arrays and objects, and return the destructured new array or new object

let arr=[1,2,3,4]
// 拓展运算符用到左侧是聚合(相当于将所有元素聚合到新数组中),用到右侧是展开
let [...a] = arr;
console.log(a);// [ 1, 2, 3, 4 ]
let obj={name:'zhangsan',age:18};
let obj1={gender:'male'}
let temp={
    ...obj,
    ...obj1
}
console.log(temp);// { name: 'zhangsan', age: 18, gender: 'male' }

2. Object Deconstruction

// 1.属性名必须和变量名一致才可以取到正确的值
let {name,a} = {name:'zhangsan',age:18}
console.log(name,a);// zhangsan undefined
let {name,age} = {name:'zhangsan',age:18}
console.log(name,age);// zhangsan 18
// 2.如果变量名和属性名不一致,需要给属性重命名
let {name:a,age:b}={name:'zhangsan',age:18}
console.log(a,b);// zhangsan 18
// 3.嵌套结构
let obj={p:['hello',{y:"world"}]};
let {p:[a,{y:b}]} = obj;
console.log(a,b);// hello world
// 4.默认值结构
let {x:y=3}={};
console.log(y);// 3

let {x:y=3}={x:6}; 
console.log(y);// 6

3. String deconstruction

// 1.可以使用对象解构或者是数组解构,使用数组结构可以获取指定字符;使用对象结构可以获取实例属性方法;
let [a,b,c]='hello';
console.log(a,b,c);// h e l
// 2.也可以将string字符串转换为数组
let [...arr]='hello';
console.log(arr);// [ 'h', 'e', 'l', 'l', 'o' ]
// 3.使用对象解构
let {toString,valueOf,length}='hello';//相当于把‘hello’当成String基本包装器类型
console.log(toString,valueOf,length)// [Function: toString] [Function: valueOf] 5

4. Numeric Deconstruction / Boolean Deconstruction

// 可以获取到数值包装器构造函数原型中指定的方法。
let {toString,valueOf}=10;
console.log(toString,valueOf)// [Function: toString] [Function: valueOf]
let {toString,valueOf}=true;
console.log(toString,valueOf);// [Function: toString] [Function: valueOf]

おすすめ

転載: blog.csdn.net/qq_50748038/article/details/126858458