ES6中的解构

解构赋值语法是一种 Javascript 表达式。通过解构赋值, 可以将属性/值从对象/数组中取出,赋值给其他变量。

1. 数组解构

//完全解构
const [a,b,c] = [3,6,9];
console.log(a,b,c);    //输出3  6  9

//嵌套解构
let [a, [b,x], c] = [1, [2, 3], 4];
console.log(a,b,x,c);

//集合解构
let [head,...tail] = [1,3,5,7];
console.log(head);
console.log(tail);


//带默认值解构
let [x,y,z] = [1,3];
console.log(x,y,z);     //1  3  undefined

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

let [d,e,f=3] = [1,2,9];
console.log(d,e,f);     //1  2  9

let [x = 1] = [null];   // x=null; 数组成员严格等于undefined,默认值才会生效

let [x = y, y = 1] = [];     // ReferenceError: y is not defined 因为x用y做默认值时,y还没有声明


//默认值可以是函数
function foo() {};
let [x=foo] = [66];
let [y=foo] = [];
console.log(x);         //66
console.log(y);         //[Function: foo]

2.对象解构

等号左边的变量放到大括号内部,匹配右侧对象中的属性


let {name,fun} = {name:'lisi',fun(){console.log("hello")}};
console.log(name,fun);

//1. 变量名的顺序可以与对象中的属性名顺序不一致
let {fun,name} = {name:'lisi',fun(){console.log("hello")}};
console.log(name,fun);     //lisi  [Function: fun]

//2. 变量名必须与对象中的属性名一致才能获取到属性值,否则获取失败,值为undefined
let {v1,v2} = {name:'wangwu',age:12};
console.log(v1,v2);     //undefined  undefined

//3. 变量重命名
let {name:v1,age} = {name:'wangwu',age:12};
console.log(v1);       //wangwu
console.log(age);      //12

//这说明对象解构赋值是以下形式的简写,冒号前的变量名用来匹配对象中的属性名,冒号后的变量名用来接收对应属性值
let {name:name, age:age} = {name:'wangwu',age:12};

//4. 嵌套解构
let {age,  outer, outer:{age:temp}} = {outer:{age:12},age:15};
console.log(age);       //15
console.log(outer);     //{ age:12 }
console.log(temp);      //12

//5. 默认值
let { f1 = 'test1', f2: rename = 'test2' , f3 = 'test3'} = { f1: 'current1', f2: 'current2'}
console.log(f1, rename, f3);        //默认值只有在解构失败的时候才生效


//6. 解构对象时会查找原型链(如果属性不在对象自身,将从原型链中查找)
var obj = {self: '123'};
obj.__proto__.prot = '456';
const {self, prot} = obj;
// self "123"
// prot "456"(访问到了原型链)

3. 字符串/数值/布尔值

// String
let [ a, b, c, ...rest ] = 'test123'
console.log(a, b, c, rest) // t, e, s, [ 't', '1', '2', '3' ]
let {length : len} = 'hello'; // en // 5
 
// number
let {toString: s} = 123;
s === Number.prototype.toString // true
 
// boolean
let {toString: s} = true;
s === Boolean.prototype.toString // true
 
// Map
let [a, b] = new Map().set('f1', 'test1').set('f2', 'test2')
console.log(a, b) // [ 'f1', 'test1' ], [ 'f2', 'test2' ]
 
// Set
let [a, b] = new Set([1, 2, 3])
console.log(a, b) // 1, 2

4.解构赋值的应用

4.1 浅拷贝

let color = ["red","blue","yellow",["green"]];
let [...cloneColor] = color;
console.log(cloneColor);	//[ 'red', 'blue', 'yellow', [ 'green' ] ]
cloneColor[3].push("pink");
console.log(cloneColor);	//[ 'red', 'blue', 'yellow', [ 'green', 'pink' ] ]
console.log(color);			//[ 'red', 'blue', 'yellow', [ 'green', 'pink' ] ]

4.2 交换变量

//交换变量的值
var a = 1;
var b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

4.3 遍历Map结构

let map = new Map();
map.set("one","timi");
map.set("two","kimi");
for(let [key,value] of map) {
    console.log(key + " is " + value);
}

4.4 函数参数解构

function add(a,b,{c,d}){
    console.log(a,b,c,d);
}
add(1,2,{});        //1  2  undefined  undefined
// add(1,2);        //Uncaught TypeError: Cannot destructure property `c` of 'undefined' or 'null'
add(1,2,3);         //1  2  undefined  undefined
add(1,2,"hello");   //1  2  undefined  undefined
add(1,2,{c:99,d:100})    //1  2  99  100

要解构成数组,右侧必须是可迭代对象;但是如果解构成对象,右侧不是null活着undefined即可!

5.基本原理

解构是ES6提供的语法糖,其实内在是针对可迭代对象的Iterator接口,通过遍历器按顺序获取对应的值进行赋值。

关于迭代协议的博客。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值