解構(gòu)賦值
核心思想——模式匹配
基本概念
用法:
- 數(shù)組解構(gòu)賦值
- 對(duì)象解構(gòu)賦值
- 字符串解構(gòu)賦值
- 數(shù)值和布爾值解構(gòu)賦值
均可設(shè)置默認(rèn)值——內(nèi)部使用'==='判斷察蹲,是否等于undefined。
基本寫(xiě)法:
- 數(shù)組的:
let [a, b, c] = [1, 2, 3];
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
let [ , , third] = ["foo", "bar", "baz"];
third // "baz"
let [x, , y] = [1, 2, 3];
x // 1
y // 3
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
- 對(duì)象的:
let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
//變量名與屬性名不同
var { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
對(duì)象的解構(gòu)賦值,要理解宰僧,匹配模式和實(shí)際的變量
- 字符串的
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
- 數(shù)值和布爾值
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
比較特殊荐健,會(huì)先將其轉(zhuǎn)換為基本包裝對(duì)象险耀。null與undefined無(wú)法轉(zhuǎn)換為對(duì)象音半。
一些問(wèn)題
- 函數(shù)參數(shù)的解構(gòu)賦值
- 注意圓括號(hào)的問(wèn)題
用途
- 交換變量值
let x = 1;
let y = 2;
[x, y] = [y, x];
- 從函數(shù)返回多個(gè)值
// 返回一個(gè)數(shù)組
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一個(gè)對(duì)象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();
- 函數(shù)參數(shù)的定義
// 參數(shù)是一組有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 參數(shù)是一組無(wú)次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
- 函數(shù)參數(shù)的默認(rèn)值
jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
}) {
// ... do stuff
};
- 提取JSON數(shù)據(jù)
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
- 遍歷Map結(jié)構(gòu)
var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world
// 獲取鍵名
for (let [key] of map) {
// ...
}
// 獲取鍵值
for (let [,value] of map) {
// ...
}
- 輸入模塊的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");