Skip to content

Latest commit

 

History

History
170 lines (134 loc) · 3.03 KB

03. 解构赋值.md

File metadata and controls

170 lines (134 loc) · 3.03 KB

解构赋值

  • 按照一定的模式,从数组和对象中提取值,对变量进行赋值
  • 使用解构赋值的特性,将会使等效的代码变得更加简洁并且可读性更高
  • 本质上,这种写法属于“模式匹配”、“映射关系”

1. 数组的解构赋值

// ES6 之前
var a=1
var b=2
var c=3

// ES6 之后
let [a,b,c] = [1,2,3]
// 对任意深度的嵌套数组进行解构
let [foo, [[bar], baz]] = [1, [[2], 3]]
// 不需要匹配的位置可以置空
[,,third] = [1, 2, 3]
// 使用...扩展运算符,匹配余下的所以值,形成一个数组
let [head, ...body] = [1, 2, 3, 4]

2. 对象的解构赋值

let { a, b } = { a: "111", z: "222" };
a // "111"
b // undefined

// 变量名与属性名不一致,可以改写成下面这样
let { a, z:b } = { a: "111", z: "222" };
a // "111"
b // "222"
// 对任意深度的嵌套对象进行解构
let itemObj = {
   arr: [
     "aaa",
     { secondLevel: "bbb" }
   ]
}
let { arr: [firstLevel, { secondLevel }] } = itemObj
console.log(firstLevel) // "aaa"
console.log(secondLevel) // "bbb"
// 自定义属性名称
let {name, id: ID} = { name: 'jack', id: 1  }

3. 字符串解构

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

let { length:len } = 'hello';
console.log(len);  //5 (长度为5)

4. 圆括号的用法

// 在解构之前就已经定义了对象
let obj;
{obj}={obj:'James'};
console.log('James');  //报错

let obj;
({obj}={obj:'James'})
console.log('James')  //James
// JS引擎 就会认为 { obj } 是一个代码块,所以等号就出问题了,解决方式是在行首放个括号(,即外包裹一层括号()

5. 实际用途

  • 交换变量的值
    let x = 1
    let y = 2
    [x, y] = [y, x]
    console.log(x)  //2
    console.log(y)  //1
  • 函数参数定义
    // 参数是一组有次序的值
    function foo([width,height,left,right]) { 
        //... 
    }
    foo([100, 200, 300, 300])
    
    // 参数是一组无次序的值
    function foo({width,height,left,right}){
         // ...
    }
    foo([left:300, width:100, right:300, height:200,])
  • 配置对象参数
    jQuery.ajax = function (url, {
          async = true,
          beforeSend = noop,
          cache = true,
          complete = noop,
          crossDomain = false,
          global = true,
          // ... 更多配置 
     }) {
          // ... 
     }
  • 从函数返回多个值
    // 返回一个数组
    function foo() {
      return [1, 2, 3]
    }
    let [a, b, c] = foo()
    
    // 返回一个对象
    function foo2() {
      return {
        a: 1,
        b: 2
      }
    }
    let { a, b } = foo2()
  • 引入模块的指定方法
    import { Loading} from 'element-ui'