结构赋值使用小技巧
1.拆分数组
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
2.便捷使用js内置对象的方法
// 例一
let { log, sin, cos } = Math;
// 例二
const { log } = console;
log('hello') // hello
- 字符串结构赋值
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
4.获取字符串的长度
let {length : len} = 'hello';
len // 5
5.结构定义函数的默认值
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
6.变量数据交换
let x = 1;
let y = 2;
[x, y] = [y, x];
7.函数的无序传参匹配
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});