|
導讀網頁的本質就是超級文本標記語言,通過結合使用其他的Web技術(如:腳本語言、公共網關接口、組件等),可以創造出功能強大的網頁。因而,超級文本標記語言是萬維網(Web)編程的基礎,也就是說萬維網是建立... 網頁的本質就是超級文本標記語言,通過結合使用其他的Web技術(如:腳本語言、公共網關接口、組件等),可以創造出功能強大的網頁。因而,超級文本標記語言是萬維網(Web)編程的基礎,也就是說萬維網是建立在超文本基礎之上的。超級文本標記語言之所以稱為超文本標記語言,是因為文本中包含了所謂“超級鏈接”點。 本篇文章給大家帶來的內容是關于ES6中解構賦值的解析(代碼示例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。ES6 允許按照一定模式,從數組和對象中提取值,對變量進行賦值,這被稱為解構(Destructuring)。 誰可以解構 數組可以用數組解構,對于 Set 結構,也可以使用數組的解構賦值。 let [x, y, z] = new Set(['a', 'b', 'c']); x // "a" 事實上,只要某種數據結構具有 Iterator 接口,都可以采用數組形式的解構賦值。 function* fibs() {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
let [first, second, third, fourth, fifth, sixth] = fibs();
sixth // 5上面代碼中,fibs是一個 Generator 函數(參見Generator 函數),原生具有 Iterator 接口。解構賦值會依次從這個接口獲取值。 解構缺少初始化報錯 當使用解構來配合var 、let或const來聲明變量時,必須提供初始化器(即等號右邊的值)。下面的代碼都會因為缺失初始化器而拋出錯誤: // 語法錯誤!
var {type,name};
// 語法錯誤!
let {type,name};
// 語法錯誤!
const {type,name};與對象解構相似,在使用var 、let 、const 進行數組解構時,你必須提供初始化器。 已聲明變量用于解構賦值 對象 // 錯誤的寫法
let x;
{x} = {x: 1};
// SyntaxError: syntax error上面代碼的寫法會報錯,因為 JavaScript 引擎會將{x}理解成一個代碼塊,從而發生語法錯誤。只有不將大括號寫在行首,避免 JavaScript 將其解釋為代碼塊,才能解決這個問題。 // 正確的寫法
let x;
({x} = {x: 1});數組 你可以在賦值表達式中使用數組解構,但是與對象解構不同,不必將表達式包含在圓括號內,例如: let colors=["red","green","blue" ], let firstColor = "black", let secondColor = "purple"; [firstColor,secondColor ] = colors; console.log(firstColor);// "red" console.log(secondColor);// "green" 解構賦值表達式的值 解構賦值表達式的值為表達式右側(在 = 之后)的值。也就是說在任何期望有個值的位置都可以使用解構賦值表達式。例如,傳遞值給函數: let node={type: "Identifier",name: "foo"},
let type = "Literal",
let name = 5;
function outputInfo(value) {
console.log(value === node); // true
}
outputInfo({type,name}=node);
console.log(type);// "Identifier"
console.log(name);// "foo"數組的解構賦值 數組解構賦值表達式的右值報錯 如果等號的右邊不是數組(或者嚴格地說,不是可遍歷的結構,參見Iterator),那么將會報錯。 // 報錯
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};一維數組的解構 let [a, b, c] = [1, 2, 3]; 上面代碼表示,可以從數組中提取值,按照對應位置,對變量賦值。 嵌套數組的解構 let [firstColor,[secondColor]] = ["red",["green","lightgreen"],"blue"]; console.log(firstColor);// "red" console.log(secondColor);// "green" 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 [a, [b], d] = [1, [2, 3], 4]; a // 1 b // 2 d // 4 let [,firstColor,[secondColor]] = ["red","blue",["green","lightgreen"]]; firstColor//blue secondColor//["green","lightgreen"] 解構不成功 當指定位置的項不存在、或其值為undefined ,則解構不成功,變量的值就等于undefined。 let [foo] = []; let [bar, foo] = [1]; 默認值 當指定位置的項解構不成功時,那么該默認值就會被使用。 let colors = ["red"]; let [firstColor,secondColor = "green"]=colors console.log(firstColor);//"red" console.log(secondColor);// "green" let [foo = true] = []; foo // true 如果默認值是一個表達式,那么這個表達式是惰性求值的,即只有在用到的時候,才會求值。 function f() {
console.log('aaa');
}
let [x = f()] = [1];上面代碼中,因為x能取到值,所以函數f根本不會執行。上面的代碼其實等價于下面的代碼。 let [x = 1, y = x] = []; // x=1; y=1 let [x = 1, y = x] = [2]; // x=2; y=2 let [x = 1, y = x] = [1, 2]; // x=1; y=2 let [x = y, y = 1] = []; // ReferenceError: y is not defined 剩余項解構 數組解構有個類似的、名為剩余項( rest items )的概念,它使用...語法來將剩余的項目賦值給一個指定的變量。 let [head, ...tail] = [1, 2, 3, 4]; head // 1 tail // [2, 3, 4] 但它還有另一個有用的功能。方便地克隆數組在 JS 中是個明顯被遺漏的功能。在ES5中開發者往往使用的是一個簡單的方式,也就是用concat() 方法來克隆數組。 var colors = ["red","green","blue"]; var clonedColors = colors.concat(); console.log(clonedColors);//"[red,green,blue]" 而在ES6中,你可以使用剩余項的語法來達到同樣效果。實現如下: let colors = ["red","green","blue"]; let [...clonedColors] = colors; console.log(clonedColors);//"[red,green,blue]" 注意!剩余項必須是數組解構模式中最后的部分,之后不能再有逗號,否則就是語法錯誤。 對象的解構賦值 解構不僅可以用于數組,還可以用于對象。對象的解構與數組有一個重要的不同。數組的元素是按次序排列的,變量的取值由它的位置決定;而對象的屬性沒有次序,變量必須與屬性同名,才能取到正確的值。 //普通對象的解構
let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
//嵌套對象的解構
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p: [x, { y }] } = obj;
//注意,這時p是模式,不是變量,因此不會被賦值。
//如果p也要作為變量賦值,可以寫成下
//let { p, p: [x, { y }] } = obj;
x // "Hello"
y // "World"
//另一個例子
const node = {
loc: {
start: {
line: 1,
column: 5
}
}
};
let { loc, loc: { start }, loc: { start: { line }} } = node;
line // 1
loc // Object {start: Object}
start // Object {line: 1, column: 5}
//注意,最后一次對line屬性的解構賦值之中,只有line是變量,loc和start都是模式,不是變量。
//默認值
var {x = 3} = {};
x // 3
var {x, y = 5} = {x: 1};
x // 1
y // 5
//默認值生效的條件是,對象的屬性值嚴格等于undefined
var {x = 3} = {x: undefined};
x // 3
var {x = 3} = {x: null};
x // null
//解構不成功,變量的值等于undefined。
let {foo} = {bar: 'baz'};
foo // undefined
// foo這時等于undefined,再取子屬性就會報錯
let {foo: {bar}} = {baz: 'baz'};
//由于數組本質是特殊的對象,因此可以對數組進行對象屬性的解構。
let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3
//length屬性
let {length : len} = [1,2,3];
len//3設置別名 ES6 有一個擴展語法,允許你在給本地變量賦值時使用一個不同的名稱。 let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'字符串的解構賦值 字符串也可以解構賦值。這是因為此時,字符串被轉換成了一個類似數組的對象。 const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o" 類似數組的對象都有一個length屬性,因此還可以對這個屬性解構賦值。 let {length : len} = 'hello';
len // 5數值和布爾值的解構賦值 解構賦值時,如果等號右邊是數值和布爾值,則會先轉為對象。 let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
let {toString} = NaN;
toString === Number.prototype.toString//true函數參數的解構賦值 函數的參數也可以使用解構賦值。 function add([x, y]){
return x + y;
}
add([1, 2]); // 3上面代碼中,函數add的參數表面上是一個數組,但在傳入參數的那一刻,數組參數就被解構成變量x和y。對于函數內部的代碼來說,它們能感受到的參數就是x和y。 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]上面代碼中,函數move的參數是一個對象,通過對這個對象進行解構,得到變量x和y的值。如果解構失敗,x和y等于默認值。當 JS 的函數接收大量可選參數時,一個常用模式是創建一個 options 對象,其中包含了附加的參數。 function move({x, y} = { x: 0, y: 0 }) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]js會先把實參傳進形參的右值,代替左值,如果沒傳,默認用形參的右值。 [1, undefined, 3].map((x = 'yes') => x); // [ 1, 'yes', 3 ] 用途 交換變量的值 let x = 1; let y = 2; [x, y] = [y, x]; 取出從函數返回的值 函數只能返回一個值,如果要返回多個值,只能將它們放在數組或對象里返回。有了解構賦值,取出這些值就非常方便。 // 返回一個數組
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一個對象
function example() {
return {
foo: 1,
bar: 2
};
}
let { foo, bar } = example();函數無次序參數的傳入 解構賦值可以方便地將一組參數與變量名對應起來。 // 參數是一組無次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});提取 JSON 數據 let jsonData = {
id: 42,
status: "OK",
data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]函數參數的默認值 jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
} = {}) {
// ... do stuff
};指定參數的默認值,就避免了在函數體內部再寫var foo = config.foo || 'default foo';這樣的語句。 遍歷 Map 結構 任何部署了 Iterator 接口的對象,都可以用for...of循環遍歷。Map 結構原生支持Iterator接口,配合變量的解構賦值,獲取鍵名和鍵值就非常方便。 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) {
// ...
}輸入模塊的指定方法 加載模塊時,往往需要指定輸入哪些方法。解構賦值使得輸入語句非常清晰。 const { SourceMapConsumer, SourceNode } = require("source-map");以上就是ES6中解構賦值的解析(代碼示例)的詳細內容,更多請關注php中文網其它相關文章! 網站建設是一個廣義的術語,涵蓋了許多不同的技能和學科中所使用的生產和維護的網站。 |
溫馨提示:喜歡本站的話,請收藏一下本站!