目录
  • 1、数组解构
  • 2、对象解构
  • 3、不完全解构
  • 4、用解构赋值实现变量交换

Javascript 解构赋值详情

1、数组解构

let [a, b, c] = [1,2,3]
console.log(a, b, c) // 1 2 3


除了数组,任何可迭代的对象都支持被解构, 例如字符串

let [first, second] = "he"

console.log(first, second) // h e

2、对象解构

赋值右侧是对象,左侧是包含在花括号内逗号隔开的变量名

let {a, b, c} = {a:1, b:2, c:3}
console.log(a,b,c) // 1 2 3


左侧的变量名需要和对象中的属性名相同,如果对应不上的话,左侧的变量名将被赋值为undefined。例如:

let {a,b, d} = {a:1, b:2, c:3}
console.log(a,b,d) // 1 2 undefined


如果变量名与属性名不一样,可以用冒号分隔符将属性名赋值给变量名

例如:

let {a,b, c:d} = {a:1, b:2, c:3}
console.log(a,b,d) // 1 2 3


3、不完全解构

解构赋值左侧变量个数可以不等于右侧数组中元素的个数

(1)左侧多余的变量会被设置为undefined,

let [a, b, c] = [1, 2]

console.log(a, b, c) // 1 2 undefined

(2)右侧多余的值将被直接忽略

let [a, b, c] = [1, 2, 3, 4]

console.log(a, b, c)  // 1 2 3


(3)左侧可以用逗号跳过某些值

let [a, , c] = [1, 2, 3, 4]

console.log(a, c)  // 1 3


(4)右侧多余的值可以通过…收集到一个变量中

let [a, b, ...c] = [1, 2, 3, 4]

console.log(a, b, c)  // 1 2 [3, 4]


4、用解构赋值实现变量交换

let a = 1, b=2;
[a, b] = [b, a]
console.log(a) //2
console.log(b) //1
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。