# 三.解构

# 1.数组变化

# 1.1 取数方式

let arr = ["xiaoming", 9]
let name = arr[0]
let age = arr[1]
1
2
3

现在

let [name, age] = ["xiaoming", 9]
1

或者只取其中一个

以前

let arr = ["xiaoming", 9]
let age = arr[1]
1
2

现在--空出来的用,分割

let [, age] = ["xiaoming", 9]
1

# 1.2 数组长度

以前

let arr = ["xiaoming", 9]
let len = arr.length
1
2

现在

let { length } = ["xiaoming", 9]
1
  • 数组必须位置相同
  • 结构更简单了,清晰明了

# 1.3 数组合并

以前

let arr = [1, 2, 3, 4, 5].concat([6, 7, 8])
console.log(arr)
1
2

现在

let arr = [...[1, 2, 3, 4, 5], ...[5, 6, 7]]
console.log(arr)
1
2

# 1.4 方法传参

以前

Math.min(1, 2, 3, 4)
1

现在

Math.min(...[1, 2, 3, 4])
1

# 2.对象变化

# 2.1 取数方式

如果有关键字可以采用:形式更改名字

let { name, age, default: d } = { name: "xiaoming", age: 9, default: "xxx" }
console.log(name, age, d)
1
2

# 2.1 设置默认值

如果想设置某个属性的默认值, 必须采用=的形式

let [
  ,
  {
    address: [, a],
  },
  hobby = "游泳",
] = [{ name: "zfpx" }, { age: 9, address: [1, 2, 4] }]
console.log(a, hobby)
1
2
3
4
5
6
7
8
  • 对象解构时名字必须相同

解构赋值 声明和赋值都放到一起了 解构 表示等号左边和右边解构类似

let { length } = ["xiaoming", 0]
console.log(length)
1
2
  • 别名默认值
let {  name: text='' } = {name:'dsasdf'} // text变量
1

# 2.3 数据拷贝

Object.assign 合并对象

let name = { name: "zbc" }
let age = { age: 9 }
let obj = Object.assign(name, age)
console.log(obj)
1
2
3
4

assign 是浅拷贝

现在更多使用这种方式

let name = { name: "zbc" }
let age = { age: 9 }
let obj = { ...name, ...age }
console.log(obj)
1
2
3
4

# 3.函数变化

function test() {
  return [1, 2, 34]
}
let [a, b, c] = test()
1
2
3
4
  • ajax 默认值
function ajax({ url = new Error("url without"), type = "get", data = "xxx" }) {
  console.log(url, type, data)
}
ajax({
  url: "/test",
  type: "get",
  data: {},
})
1
2
3
4
5
6
7
8

# 2.解构赋值

  • 1.解构数组

解构的意思是分解一个东西的结构,可以用一种类似数组的方式定义 n 个变量,可以将一个数组中的值按照规则赋值过去

var [name, age] = ["abc", 8]
console.log(name, age)
1
2
  • 2.嵌套赋值
let [x, [y], z] = [1, [2], 3]
console.log(x, y, z)
let [x, [y, z]] = [1, [2, 3]]
console.log(x, y, z)
let [json, arr, num] = [{ a: 1 }, [1, 2, 3], 5]
console.log(json, arr, num)
1
2
3
4
5
6
  • 3.省略赋值
let [, , c] = [1, 3, 4]
console.log(c)
1
2
  • 4.结构对象
var obj = { name: "abc", age: 8 }
//对象里的name属性的值会交给name这个变量,age的值会交给age这个变量
var { name, age } = obj
//对象里的name属性的值会交给myname这个变量,age的值会交给myage这个变量
let { name: myname, age: myage } = obj
console.log(name, age, myname, myage)
1
2
3
4
5
6
  • 5.默认值

在赋值和传参的时候可以使用默认值

let [a = "a", b = "b", c = new Error("C必须指定")] = [1, , 3]
console.log(a, b, c)

function ajax(options) {
  var method = options.method || "get"
  var data = options.data || {}
  //.....
}
function ajax({ method = "get", data }) {
  console.log(arguments)
}
ajax({
  method: "post",
  data: { name: "abcd" },
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 3.数据拷贝

...是浅拷贝

let name = { name: "zpx" }
let age = { age: 9 }
let school = { ...name, ...age }
console.log(school)
1
2
3
4
  • slice 是浅拷贝 如果拷贝一层就是深拷贝
let b = [1, 2, 3, 4]
let a = [b]
let c = a.slice(0)
b[0] = 100
console.log(c)
1
2
3
4
5