一.()用法
变为表达式而不是作用域
let a (xxx)//这样写会报错
let a;
({a}={a:1});
console.log(a);//1
对象属性得模式匹配
let a1 = [1, 2, 3], obj = {};
[obj2.a,obj2.b,obj.c] = a1;
console.log(obj2.a, obj.b, obj2.c);//1 2 3
()的合法性
let [(a)] = [1];
let ({a:b}) = {};
let {(a):b} ={};
let {a: (b)} = {};
function foo(([z])){
return z
}
console.log(foo([1]));
var [(a)] = [1];
var({a:b}) = {};
var{(a):b} ={};
var{a: (b)} = {};
//以上都不行 用let方式的申明所有()报错 let is not defined
二.解构的本质
示例
let arr = [1, 2, 3];
let {0: first,[arr.length-1]:last} = arr;//打印了1和3 数组也是特殊的对象
[(b)] = [3]
console.log(b);//输出3
({a:(b)={}})
console.log(b);//打印{} 本身打印出值,但其实并没有匹配
var a = {};
[(a.b)] = [3];
console.log(a.b)//打印3
let a = 'x', b = 'y', obj = {};
({a:obj[a+b]} = {a:2});
console.log(obj)//打印Object xy:2 _proto_:Object去掉括号会报错
let obj1 = {a:1,b:2,c:3},obj2={};
({a:obj2.x,b:obj2.y,c:obj2.z} = obj1);
console.log(obj2.x,obj2.y,obj2.z);//打印123
//完成交换值
let a = 10, b = 20;
[b,a] = [a,b]
变量的解构就是变量的赋值
需要注意
//对象匹配允许同源匹配
let {a: x,a: x} = {a: 1};
console.log(x,x)//会报错,不要重复定义
let {a: x,a: y} = {a: 1};
console.log(x,y);//这样也是可以的
let person = {
son:{
name:'wangwu',
ageWang:18,
son:{
name:'zza'
}
}
}
let {son:{son:{name}}}} = person//嵌套取值 主张通过缩进来写不然很很乱
默认值的问题
var x = 200, y = 300, z = 100;
var obj1 = {x: {y:42},z:{y:z}}
({y:x = {y:y}} = obj1) //300 y:x = {y :300} 传入值为空
({z:y = {y:z}} = obj1) //100 z:y = {y: 100} 传入值为空
({x:z = {y:x}} = obj1) //42 x:z = {y: 200} = x:{y:42}
log(x.y,y.y,z.y)//300 100 42
在解构中使用对象或是数组的时候,慎用(可读性非常差)
三.函数参数解构
示例
数组
function test([x, y]){
console.log(x);
console.log(y);
}
test([1, 2]);//打印1,2
对象
function foo({x, y}){
console.log(x,y)
}
foo({x: 1, y:2})//打印1,2
调换顺序也可以
function foo({x, y}){
console.log(x, y);
}
foo({y: 1, x:2})//打印1,2
参数不全的情况
function foo({x,y}){
console.log(x, y);
}
foo({x: 1})//给一个参数undefined 两个都不传就是两个undefined
对象默认值的问题
function foo({x = 10} = {}, {y} = {y:10}){
console.log(x, y)
}
foo();//10 ,10
foo({},{}) //10 un
foo({x:2},{y:3});// 2 3
分解
({x: x = 10} = {})
console.log(x) //10
({y: y} = {y: 10})
console.log(y) //10
四.隐式转换
//字符串转数组
const [a, b, c, d, e] = 'hello';
console.log(a, b, c, d, e); //输出h e l l o
//调用属性
let {length: len} = 'hello';
console.log(len);//输出5
let {toString: s} = 123;
console.log(s);//输出f tostring(){[native code]}
console.log(s === Number.prototype.toString)//true
let {toString: s} = true;
console.log(s === Boolean.prototype.toString)//true
布尔值,number,string都能进行隐式转换
let {prop} = null;
log(prop);
//undefined,null不能进行隐式转换