溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ES6z2數(shù)組解構(gòu)和字符串解構(gòu)的示例分析

發(fā)布時(shí)間:2021-08-25 14:07:51 來源:億速云 閱讀:130 作者:小新 欄目:web開發(fā)

這篇文章將為大家詳細(xì)講解有關(guān)ES6z2數(shù)組解構(gòu)和字符串解構(gòu)的示例分析,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

具體如下:

ES6 允許按照一定模式,從數(shù)組和對象中提取值,對變量進(jìn)行賦值,這被稱為解構(gòu)(Destructuring), 而數(shù)組的解構(gòu)賦值是從數(shù)組中提取值,按照對應(yīng)位置,對變量賦值。

ES6之前的賦值操作

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

對一維數(shù)組的解構(gòu)賦值的應(yīng)用

var arr = [1,2,3];
var [a,b,c] = arr;
console.log(a,b,c); // 1 2 3

對多維數(shù)組的解構(gòu)賦值的應(yīng)用

let arr = [22, [5,8], 11];
let [a,[b,c],d] = arr;
console.log(a,b,c,d); // 22 5 8 11

解構(gòu)賦值用于變量的交換舉例

let x = 11;
let y = 22;
[y,x] = [x,y];
console.log(x,y); // 22 11

解構(gòu)賦值中不完全的解析示例

let arr = [22, [5,8], 11];
let [a,[b],c] = arr;
console.log(a, b, c); // 22 5 11
let [m,[,n],o] = arr;
console.log(m, n, o); // 22 8 11

不能被數(shù)組解析的值

let [m] = "";
console.log(m); // undefined;
let [x,y] = NaN; // NaN is not iterable. 不能被數(shù)組解析的值:NaN, undefined, null, {}

實(shí)現(xiàn)了iterator接口的類型都可以被解析賦值

let [x,y] = new Set([22, 33]);
console.log(x,y); // 22 33

自己創(chuàng)造一個(gè)實(shí)現(xiàn)iterator接口的對象進(jìn)行解構(gòu)賦值

class Group{
 constructor() {
 }
 next() {
  return {value:'Joh', done: false};
 }
 [Symbol.iterator]() {
  return this;
 }
}
let group = new Group();
let [x,y,z,m,n] = group;
console.log(x,y,z,m,n); // Joh Joh Joh Joh Joh 備注:這里如果類中的next的done為true,那么全為undefined

… 運(yùn)算符 轉(zhuǎn)換成數(shù)組的解構(gòu)舉例

var [x,w, ...y] = [1,2,3,4,5,6];
console.log(x,w, y); // 1 2 [3,4,5,6]

解構(gòu)數(shù)組的默認(rèn)值

如果數(shù)組中的不是undefined,都會被成功解構(gòu), 不會被默認(rèn)值替代

let [x=15, y] = [undefined, 12];
console.log(x,y); // 15 12
let [m=12, n] = [null, 10];
console.log(m, n); // null 10

字符串解構(gòu)的處理

var [a,b,c] = 'hello';
console.log(a,b,c); // h e l

關(guān)于“ES6z2數(shù)組解構(gòu)和字符串解構(gòu)的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯(cuò),請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

es6
AI