解构赋值笔记

May 31, 2020 默认分类

解构赋值

解构赋值(Destructuring assignment)可以将数组或对象“拆包”为到一系列变量中

MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
现代 JavaScript 教程: https://zh.javascript.info/destructuring-assignment
ECMAScript 6 入门: https://es6.ruanyifeng.com/#docs/destructuring

Array

let first,second;
[first,second] = ["one","two"]; // first="one",second="two"

// 忽略使用逗号的元素
let [m,,n] = [9,8,7]; // m=9,n=7

// 展开语法(Spread syntax),剩余元素
let [x, y, ...z] = [1,2,3,4,5]; // x=1,y=2,z=[3,4,5]

// 注意事项,剩余元素必须是数组的最后一个元素
var [a, ...b,] = [1, 2, 3];
// SyntaxError: rest element may not have a trailing comma

// 默认值,匹配结果是 undefined 时返回
let [name = "Guest", surname = "Anonymous"] = ["Julius"];
alert(name);    // Julius(来自数组的值)
alert(surname); // Anonymous(默认值被使用)

// 赋值给等号左侧的任何内容(Iterator)
let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);

// 循环遍历键—值对
let user = {
  name: "John",
  age: 30
};

for (let [key, value] of Object.entries(user)) {
  alert(`${key}:${value}`); // name:John, then age:30
}

Object

/* 基本 */
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
// foo = 'aaa'
// bar = 'bbb'
 
let { baz : foo } = { baz : 'ddd' };
// foo = 'ddd'

/* 可嵌套可忽略 */
let obj = {p: ['hello', {y: 'world'}] };
let {p: [x, { y }] } = obj;
// x = 'hello'
// y = 'world'
let obj = {p: ['hello', {y: 'world'}] };
let {p: [x, {  }] } = obj;
// x = 'hello'

/* 不完全解构 */
let obj = {p: [{y: 'world'}] };
let {p: [{ y }, x ] } = obj;
// x = undefined
// y = 'world'

/* 剩余运算符 */
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
// a = 10
// b = 20
// rest = {c: 30, d: 40}

/* 解构默认值 */
let {a = 10, b = 5} = {a: 3};
// a = 3; b = 5;
let {a: aa = 10, b: bb = 5} = {a: 3};
// aa = 3; bb = 5;

添加新评论