詳解JS ES6變量的解構(gòu)賦值
1.什么是解構(gòu)?
ES6允許按照一定模式,從數(shù)組和對(duì)象中提取值,對(duì)變量進(jìn)行賦值,這被稱為解構(gòu)。它在語法上比ES5所提供的更加簡(jiǎn)潔、緊湊、清晰。它不僅能減少你的代碼量,還能從根本上改變你的編碼方式。
2.數(shù)組解構(gòu)
以前,為變量賦值,我們只能直接指定值,比如
let a = 1; let b = 2; let c = 3;
現(xiàn)在可以用數(shù)組解構(gòu)的方式來進(jìn)行賦值
let [a, b, c] = [1, 2, 3]; console.log(a, b, c); // 1, 2, 3
這是數(shù)組解構(gòu)最基本類型的用法,還可以解構(gòu)對(duì)象數(shù)組
// 對(duì)象數(shù)組解構(gòu)
let [a, b, c] = [{name: 'jacky'}, {name: 'monkey'}, {name: 'houge'}];
console.log(a, b, c); // {name: 'jacky'}, {name: 'monkey'}, {name: 'houge'}
3.數(shù)組模式和賦值模式統(tǒng)一
這條可以理解為等號(hào)左邊和等號(hào)右邊的形式要統(tǒng)一,如果不統(tǒng)一解構(gòu)將失敗。
let [a, [b, c], d] = [1, [2, 3], 4];
console.log(a, b, c, d); // 1 2 3 4
// 提取除第二、三個(gè)外的所有數(shù)值
let [a, , , d] = [1, 2, 3, 4];
console.log(a, d); //1 4
let [a, ...b] = [1, 2, 3, 4];
console.log(a, b); // 1 [2, 3, 4]
let [a, , , ...d] = [1, 2, 3, 4, 5];
console.log(a, d); // 1 [4, 5]
如果解構(gòu)不成功,變量的值就等于undefined
let [a, b, c] = [2, 3];
console.log(a, b, c); // 2 3 undefined
let [c] = [];
console.log(c); // undefined
如果解構(gòu)不成功,變量的值就等于undefined
let [a, b, c] = [2, 3]; console.log(a, b, c); // 2 3 undefined let [c] = []; console.log(c); // undefined
上述是完全解構(gòu)的情況,還有一種是不完全解構(gòu),即等號(hào)左邊的模式,只匹配一部分的等號(hào)右邊的數(shù)組,解構(gòu)依然可以成功。
let [x, y] = [1, 2, 3]; console.log(x, y); // 1 2 let [a, [b], d] = [1, [2, 3], 4]; console.log(a, b, d); // 1 2 4
4.解構(gòu)的默認(rèn)值
解構(gòu)賦值允許指定默認(rèn)值。
let [a, b=2] = [1]; console.log(a, b); // 1 2 let [a=1, b=2, c, d=13] = [10, 11, 12]; console.log(a, b, c, d); // 10 11 12 13
5.對(duì)象的解構(gòu)賦值
對(duì)象的解構(gòu)與數(shù)組有一個(gè)重要的不同。數(shù)組的元素是按次序排列的,變量的取值由它的位置決定;而對(duì)象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值。
// 對(duì)象解構(gòu)賦值的內(nèi)部機(jī)制,是先找到同名屬性,然后再賦給對(duì)應(yīng)的變量。真正被賦值的是后者,而非前者。
let obj = { a: "aaa", b: "bbb" };
let { a: x, b: y } = obj;
console.log(x, y); // aaa bbb
let { a, b } = { a: 'aaa', b: 'bbb' };
console.log(a, b); // aaa bbb
// 不按照順序
let { b, a } = { a: 'test1', b: 'test2' }
console.log(a, b) // test1 test2
// 嵌套解構(gòu)
let { obj: { name }} = { obj: { name: 'jacky', age: '22' } }
console.log(name) // jacky
// 稍微復(fù)雜的嵌套
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p: [x, { y }] } = obj;
console.log(x, y); // Hello World
如果變量名與屬性名不一致,必須寫成下面這樣。
var { foo: rename } = { foo: "aaa",bar: "bbb" };
console.log(rename); // aaa
console.log(foo); // Uncaught ReferenceError: foo is not defined
如果在解構(gòu)之前就定義了變量,這時(shí)候再解構(gòu)會(huì)出現(xiàn)問題。下面是錯(cuò)誤的代碼,編譯會(huì)報(bào)錯(cuò)(因?yàn)閖s引擎會(huì)將{a}理解成一個(gè)代碼塊,從而發(fā)生語法錯(cuò)誤。只有不將大括號(hào)寫在行首,避免js將其解釋成代碼塊,才能解決這個(gè)問題)
let a;
let obj = { a: "aaa" };
{a} = obj; // Uncaught SyntaxError: Unexpected token '='
要解決報(bào)錯(cuò),使程序正常,這時(shí)候只要在解構(gòu)的語句外邊加一個(gè)圓括號(hào)就可以了
let a;
let obj = { a: "aaa" };
( {a} = obj );
console.log(a); // aaa
6.函數(shù)參數(shù)
函數(shù)的參數(shù)也可以使用解構(gòu)賦值。
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
函數(shù)參數(shù)的解構(gòu)也可以使用默認(rèn)值。
function fn(x, y = 7) {
return x + y;
}
console.log(fn(3)); // 10
7.字符串解構(gòu)
字符串被轉(zhuǎn)換成了一個(gè)類似數(shù)組的對(duì)象。
const [a, b, c, d, e, f] = "hello"; console.log(a); //h console.log(b); //e console.log(c); //l console.log(d); //l console.log(e); //o console.log(f); //undefined
8.數(shù)值和布爾值的解構(gòu)賦值
解構(gòu)賦值時(shí),如果等號(hào)右邊是數(shù)值和布爾值,則會(huì)先轉(zhuǎn)為對(duì)象。
let {toString: s} = 0;
console.log(s === Number.prototype.toString); // true
let {toString: s} = true;
console.log(s === Boolean.prototype.toString); // true
解構(gòu)賦值的規(guī)則是,只要等號(hào)右邊的值不是對(duì)象或數(shù)組,就先將其轉(zhuǎn)為對(duì)象。由于undefined和null無法轉(zhuǎn)為對(duì)象,所以對(duì)它們進(jìn)行解構(gòu)賦值,都會(huì)報(bào)錯(cuò)
let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
9.解構(gòu)賦值的應(yīng)用
1.交換變量的值
通常交換兩個(gè)變量的方法需要一個(gè)額外的臨時(shí)變量,如下
let a = 1; let b = 2; let temp; temp = a; a = b; b = temp; console.log(a, b); // 2 1
用ES6解構(gòu)賦值的話,會(huì)變得很簡(jiǎn)潔
let a = 1; let b = 2; [a, b] = [b ,a]; console.log(a, b); // 2 1
2.從函數(shù)返回多個(gè)值
函數(shù)只能返回一個(gè)值,如果要返回多個(gè)值,只能將它們放在數(shù)組或?qū)ο罄锓祷亍S辛私鈽?gòu)賦值,取出這些值就非常方便。
// 返回一個(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();
3.訪問數(shù)組中元素
有種場(chǎng)景,比如有一個(gè)數(shù)組(可能為空)。并且希望訪問數(shù)組的第一個(gè)、第二個(gè)或第n個(gè)項(xiàng),但如果該項(xiàng)不存在,則使用指定默認(rèn)值。
通常會(huì)使用數(shù)組的length屬性來判斷
const list = [];
let firstItem = 'hello';
if (list.length > 0) {
firstItem = list[0];
}
console.log(firstItem); // hello
如果用ES6解構(gòu)賦值來實(shí)現(xiàn)上述邏輯
const list = []; const [firstItem = 'hello'] = list; console.log(firstItem); // 'hello'
4.提取 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]
5.遍歷 Map 結(jié)構(gòu)
任何部署了 Iterator 接口的對(duì)象,都可以用for...of循環(huán)遍歷。Map 結(jié)構(gòu)原生支持 Iterator 接口,配合變量的解構(gòu)賦值,獲取鍵名和鍵值就非常方便。
const 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) {
// ...
}
以上就是詳解JS ES6變量的解構(gòu)賦值的詳細(xì)內(nèi)容,更多關(guān)于JS ES6變量解構(gòu)賦值的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
js實(shí)現(xiàn)簡(jiǎn)單的點(diǎn)名器隨機(jī)色實(shí)例代碼
這篇文章主要給大家介紹了關(guān)于js實(shí)現(xiàn)簡(jiǎn)單的點(diǎn)名器隨機(jī)色的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
原生JS實(shí)現(xiàn)網(wǎng)頁手機(jī)音樂播放器 歌詞同步播放的示例
下面小編就為大家分享一篇原生JS實(shí)現(xiàn)網(wǎng)頁手機(jī)音樂播放器 歌詞同步播放的示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-02-02
JavaScript操作DOM元素的childNodes和children區(qū)別
這篇文章主要介紹了JavaScript操作DOM元素的childNodes和children區(qū)別,本文直接給出測(cè)試代碼和運(yùn)行效果來講解它們之間的區(qū)別,需要的朋友可以參考下2015-04-04
js通過var定義全局變量與在window對(duì)象上直接定義屬性的區(qū)別說明
這篇文章主要介紹了js通過var定義全局變量與在window對(duì)象上直接定義屬性的區(qū)別說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
js實(shí)現(xiàn)點(diǎn)擊獲取驗(yàn)證碼倒計(jì)時(shí)效果
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)點(diǎn)擊獲取驗(yàn)證碼倒計(jì)時(shí)效果,這種效果大家經(jīng)常遇到,示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2015-10-10

