在前后台数据交互时,特别的实用方便
数组的解构赋值:
let [a, b, c] = [1, 2, 3]; console.log(a , b, c); // 1 2 3
对象的解构赋值:
let {name, age} = { name: "tales", age: 27 } console.log(name, age); // tales 27
解构赋值 -> 设置别名 (对象解构赋值生效)
let {name, age:myage} = { name: "tales", age: 27 } console.log(name, myage); // tales 27
解构赋值 -> 设置默认值
let [a, b, c='a'] = [1, 2]; console.log(a , b, c); // 1 2 'a' let {name, age:myage, hobby='t'} = { name: "tales", age: 27 } console.log(name, myage, hobby); // tales 27 t
数据交换
let h = 12; let y = 5; [h,y] = [y, h]; console.log(h,y); // 5 12
函数的解构赋值
function fn({a,b, c=5}){ console.log(a, b, c); // 1 3 5 } fn({ a: 1, b: 3 }); //不传参 function fn({a=1,b=2, c=5}={}){ console.log(a, b, c); // 1 2 5 } fn();