- 按照一定的模式,从数组和对象中提取值,对变量进行赋值
- 使用解构赋值的特性,将会使等效的代码变得更加简洁并且可读性更高
- 本质上,这种写法属于“模式匹配”、“映射关系”
// 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]
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 }
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)
// 在解构之前就已经定义了对象
let obj;
{obj}={obj:'James'};
console.log('James'); //报错
let obj;
({obj}={obj:'James'})
console.log('James') //James
// JS引擎 就会认为 { obj } 是一个代码块,所以等号就出问题了,解决方式是在行首放个括号(,即外包裹一层括号()
-
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'
![](https://camo.githubusercontent.com/60d47f477e7d0c6b5740a3a3ecb371f1c94bc52fc63329d7a9eb414797acb0f4/68747470733a2f2f7777772e7733637363686f6f6c2e636e2f6174746163686d656e74732f696d6167652f32303138313230352f313534333937373637333438333536352e6a7067)