解构赋值
ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构 Destructuring
let a = 1;
let b = 2;
let c = 3;
let [a,b,c] = [1, 2, 3]
解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。
函数的参数也可以使用解构赋值
function add([a,b]){ return a + b; }
add([1,2])
用途
提取 json 数据
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]