js數組扁平化


1.偶然發現了yield*的用法,天才級別的扁平化方式

  function* iterTree(tree){
      if(Array.isArray(tree)){
          for(let i = 0 ;i<tree.length;i++){
              yield* iterTree(tree[i]);
          }
      }else{
          yield tree;
      }
  }
 let arr1 = [1, 2, ['a', 'b', ['中', '文', [1, 2, 3, [11, 21, 31]]]], 3];
for (const x of iterTree(tree)) {
      console.log(x);
  }

2.利用Array.some方法判斷數組中是否還存在數組,es6展開運算符連接數組

function iterTree2(arr) {
    while (arr.some(item => Array.isArray(item))) {
        arr = [].concat(...arr);
    }
    return arr;
}
console.log(iterTree2(arr1));

3.利用array數組的reduce屬性,reduce回調函數有四個參數,reduce(( previousValue,currentValue,currentIndex,array)=>{},initial)

   提供了initial的值的時候,previousValue為initial的大小,currentValue為數組的第一個元素值
   沒有提供initial的值的時候,preciousValue為數組第一個元素的值,currentValue為第二個元素的值,此后每執行一次,previousValue
function iterTree3(arr) {
    var newArr = arr.reduce((prev, current) => {
         return prev.concat(Array.isArray(current) ? iterTree3(current) : current)
    }, []);
    return newArr;
}
console.log(iterTree3(arr1));

4.es6中的flat函數也可以實現數組的扁平化

let arr1 = [1,2,['a','b',['中','文',[1,2,3,[11,21,31]]]],3];
 console.log( arr1.flat( Infinity ) ); 

目前就這么多吧。。============================================================想到的時候再來


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM