1. 程式人生 > 程式設計 >JS陣列降維的實現Array.prototype.concat.apply([], arr)

JS陣列降維的實現Array.prototype.concat.apply([], arr)

把多維陣列(尤其是二維陣列)轉化為一維陣列是業務開發中的常用邏輯,最近跟著黃軼老師學習Vue2.6.1.1版本原始碼時,看到原始碼對二維陣列降維的程式碼,所以這裡來寫一篇,記錄一下,加強印象

二維陣列降為一維陣列

迴圈降維

let children = [1,2,3,[4,5,6],7,8,[9,10]];
function simpleNormalizeChildren(children) {
 let reduce = [];
 for (let i = 0; i < children.length; i++) {
  if (Array.isArray(children[i])) {
   for (let j = 0; j < children[i].length; j++) {
    reduce.push(children[i][j]);
   }
  } else {
   reduce.push(children[i]);
  }
 }
 return reduce;
}
simpleNormalizeChildren(children) // [1,4,6,9,10]

此方法思路簡單,利用雙重迴圈遍歷二維陣列中的每個元素並放到新陣列中。

concat降維

MDN上對於concat的介紹

“concat creates a new array consisting of the elements in the object on which it is called,followed in order by,for each argument,the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array).”

concat

如果concat方法的引數是一個元素,該元素會被直接插入到新陣列中;如果引數是一個數組,該陣列的各個元素將被插入到新陣列中;將該特性應用到程式碼中:

let children = [1,10]];
function simpleNormalizeChildren(children) {
 let reduce = [];
 for (let i = 0; i < children.length; i++) {
  reduce = reduce.concat(children[i]);
 }
 return reduce;
}
simpleNormalizeChildren(children) // [1,10]

children 的元素如果是一個數組,作為concat方法的引數,陣列中的每一個子元素會被獨立插入進新陣列。利用concat方法,我們將雙重迴圈簡化為了單重迴圈。

apply和concat降維

MDN上對於apply方法的介紹

“The apply() method calls a function with a given this value and arguments provided as an array.”

apply

apply方法會呼叫一個函式,apply方法的第一個引數會作為被呼叫函式的this值,apply方法的第二個引數(一個數組,或類陣列的物件)會作為被呼叫物件的arguments值,也就是說該陣列的各個元素將會依次成為被呼叫函式的各個引數;將該特性應用到程式碼中:

let children = [1,10]];
function simpleNormalizeChildren(children) {
 return Array.prototype.concat.apply([],children);
}
simpleNormalizeChildren(children) // [1,10]

children作為apply方法的第二個引數,本身是一個數組,陣列中的每一個元素(還是陣列,即二維陣列的第二維)會被作為引數依次傳入到concat中,效果等同於[].concat(1,10])。利用apply方法,我們將單重迴圈優化為了一行程式碼

Vue2.6.11版本原始碼降維

let children = [1,10]];
// :any 可以去掉 這裡是Vue通過Flow指定傳入的引數型別可以是任意型別
function simpleNormalizeChildren(children: any) {
 for (let i = 0; i < children.length; i++) {
  if (Array.isArray(children[i])) {
   return Array.prototype.concat.apply([],children);
  }
 }
 return children;
}

simpleNormalizeChildren(children); // [1,10]

多維陣列降為一維陣列

遞迴降維

遞迴函式就是在函式體內呼叫自己;

遞迴函式的使用要注意函式終止條件避免死迴圈;

// 多維陣列
let children = [1,[2,3],[5,[7,8]]],10]];
function simpleNormalizeChildren(children) {
 for (let i = 0; i < children.length; i++) {
  if (Array.isArray(children[i])) {
   children = Array.prototype.concat.apply([],children);
   for(let j =0; j<children.length; j++) {
    simpleNormalizeChildren(children)
   }
  }
 }
 return children;
}
simpleNormalizeChildren(children); // [1,10]

到此這篇關於JS陣列降維的實現Array.prototype.concat.apply([],arr)的文章就介紹到這了,更多相關JS陣列降維內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!