【赋值解构】

1,331 阅读3分钟

记录自己觉得有用且易遗忘的知识点

赋值解构

新的变量赋值方式
优美且简洁的代码
保护内容,只可读

赋值解构

字符串解构

const [a, b, c, d, e, f, g] = "lindada";
console.log(a, b, c, d, e, f, g);  // => l i n d a d a

数值解构

可以解构数值原型Number中的内容

const { toString: s } = 123;
console.log(s);    // [Function: toString]
console.log(s === Number.prototype.toString);    // true

布尔解构

可以解构布尔值原型Boolean中的内容

const { toString: b } = true;
console.log(b);    // [Function: toString]
console.log(b === Boolean.prototype.toString);    // true

函数参数解构

数组参数

Func([1, 2, 3])
function Func([x1, x2, x3]) {
	console.log(x1, x2, x3)   // 1 2 3
}

对象参数

Func({
	name: '大大',
	age: 20
})
function Func({name, age}) {
	console.log(name, age)   // 大大 20
}

数组解构

形式

const [a, b, c] = [0, 1, 2];
console.log(a, b, c);    // 0 1 2

默认

const [x, y = 2] = [1]    // 默认赋值均为1
console.log(x, y)   // 1 2

对象解构

形式

const {name, age} = { name: '大大', age: 20 };
console.log(name, age);    // 大大 20

默认

const {name, age, dream = 'happy'} = { name: '大大', age: 20 };
console.log(name, age, dream);    // 大大 20 happy

改名

const { name, age: years } = { name: '大大', age: 20 }
console.log(name, years);    // 大大 20

注意

无解构变量

例如对象解构

const {name, age, dream} = { name: '大大', age: 20 };
console.log(name, age, dream)   // 大大 20 undefined

undefined 和 null

无法转为对象 -> 无法进行解构

const [ u1 ] = undefined
console.log(u1)    // TypeError: undefined is not iterable
const { u2 } = undefined
console.log(u2)    // TypeError: Cannot destructure property 'u2' of 'undefined' as it is undefined.
const [ n1 ] = null
console.log(n1)    // TypeError: null is not iterable
const { n2 } = null
console.log(n2)    // TypeError: Cannot destructure property 'n2' of 'null' as it is null.

解构与扩展运算符

const [a, ...b] = "lindada";
console.log(a, b);  // => l [ 'i', 'n', 'd', 'a', 'd', 'a' ]

用处

交换变量的值

代码交换变量x和y的值,简洁,易读,语义非常清晰

let x = 1;
let y = 2;
[x, y] = [y, x];
console.log(x, y);   // 2 1

从函数返回多个值

函数只能返回一个值,如果要返回多个值,解构取出

返回一个数组

function example() {
	return [1, 2, 3];
}
let [a, b, c] = example();
console.log(a, b, c)    // 1 2 3

返回一个对象

function example() {
	return {
		name: '大大',
		age: 20
	};
}
let { name, age } = example();
console.log(name, age)    // 大大 20

提取 JSON 数据

简洁,明了地提取 JSON 对象中的数据

let json = {
	id: 42,
	code: 200,
	data: {
		name: "大大",
		age: 20
	}
};

let { id, code, data: info } = json;

console.log(id, code, info);    // 42 200 { name: '大大', age: 20 }

遍历 Map 结构

配合变量的解构赋值,获取键名和键值非常方便。

const map = new Map();
map.set('name', '大大');
map.set('age', 20);

for (let [key, value] of map) {
	console.log(key + " is " + value);
}
// name is 大大
// age is 20

输入模块的指定方法

加载模块时,指定输入哪些方法。

const { method1, method2, method3 } = import(xxx.js)

结尾

ES6 随笔【赋值解构】
ES6 随笔【奇形怪状】
博客原文✨
参考 JowayYoung 大佬的文章 - 1.5万字概括ES6全部特性(已更新ES2020)

最后想说

  • 记录下自己复习的点点滴滴
  • 让以后的自己感到骄傲
  • 要是本文章(笔记)有任何需要修改或注意的地方,麻烦联系我噢!小编卑微整改