ES6解构赋值
解构:ES6中允许按照一定的模式,从数组和对象中提取相关的信息片段,然后对变量进行赋值,常见的解构赋值:数组,对象, 字符串...
- 数组解构
let [a, b, c] = [10, 20, 30] console.log(a, b, c) // 10, 20, 30 let [a, b, c] = [{ name: 1}, { name: 2}, { name: 3}] console.log(a, b, c) // {name: 1}, {name: '2'}, {name: '3'} let [a, ...rest] = [1,2,3,4,5] console.log(a, rest) // 1, [2,3,4,5] let [a, [b], c] = [1, [2, 3], 4] console.log(a, b, c) // 1 [2, 3], 4 let [a, b, c] = [1] console.log(a, b, c) // 1, undefined, undefined [默认解构] let [x = 1] = [undefined] // x = 1 let [x = 1] = [null] // x = null let [x = 1, y = x] = [2] // x = 2 y = 2 let [x = 1, y = x] = [1, 2] // x = 1 y = 2 let [x = y, y = 1] = [] // 报错
- 对象的解构
对象的具有相同的变量的位置,可以提起对象中对应的变量值, 数组的元素是按次序排列的,变量的取值有它的位置决定; 对象的属性没有次序,变量必须和属性同名,才能取到对应的值
let {a, b} = { a: 1, b: 2} // a=1 b=2 let {a, b} = { b: 3, a: 4} // a=4 b=3 let { c } = { b: 3, a: 4} // undefined [修改变量名] let { foo: baz} = { foo: 'aaa', bar: 'bbb'} // baz='aaa' let { first: f, last: l } = { first: 'hello', last: 'world'} // f:hello l:world [对象解构的内部机制:先找到同名属性,然后在赋值对应的变量] let { foo: foo, bar: bar} = { foo: 'aaa', bar: 'bbb'} [解构的嵌套结构的对象] let obj = { p: [ "hello", { y: 'world'} ] } let { p: [x, {y}]} = obj // x: hello y:world [对象的解构默认值]: 默认值生效的条件是,对象的属性值严格等于undefined let {x = 3} = {} // x = 3 let {x, y = 5} = { x: 1} // x=1 y= 5 let { x: y=3} = {} // y=3 let { message: msg="something went wrong"} = {} // msg=something went wrong
- 字符串的解构赋值
字符串的解构赋值,实质就是把字符串被转换成了一个类似数组的对象
const [a, b, c, d, e] = 'hello' let { length: len} = 'hello' // 5
- 数值和布尔的解构赋值
解构赋值时,如果等号右边的数值是布尔值,则会先转化为对象 解构的规则是:只要等号右边的值不是对象或数组,就将其先转化对象,由于undefined和null 无法转换为对象,所以对他们进行解构赋值就是报错
let { toString: s} = 123 // s: 123 s === Number.prototype.toString true let { toString: s} = true // s === Boolean.prototype.toString // true
- 函数参数的解构赋值
function add([x,y]) { return x + y } add([1, 2]) function move({x=0, y=0} = {}) { return [x, y] } move({ x:3, y: 8}) // [3, 8] move({ x:3}) // [3, 0] move({}) // [0, 0] move() // [0, 0] [for 循环] var arr = [[11, 12], [21, 22], [31, 32]] for (let [a, b] of arr) { console.log(a, b) } [循环解构对象] var arr = [{ name: 'chris', age: 26}, { name: 'jack', age: 27}, { name: 'peter',age: 28}]; for (let {age, name} of arr) { console.log(name, age) }
- 应用情况
- 在等号赋值或for循环中,如果需要从数组或对象中取值,尽量使用解构
- 在自己定义函数是,如果调用者传来的是数组和对象,形参尽量使用解构方式,优先使用对象解构,其次是数组解构
- 在调用第三方函数的时候,如果该函数接受多个参数,并且传入的是数组,则使用扩展运算符