Vue源码 --- 二维数组转换成一维数组

Vue源码中用到的二维数组 -> 一维数组

ES5:

function normalizeArr(children) {
  for(let i = 0; i< children.length; i++) {
    if(Array.isArray(children[i])) {
      return Array.prototype.concat.apply([], children);
    }
  }
  return children;
}

var arr = [1,2,3,[4,5,6]];
[ 1, 2, 3, 4, 5, 6 ]

ES6:

var arr = [['1', '1_1'], ['2','2_1', ['3', '3_1']]]
// 2为数组嵌套的层次
arr.flat(2);//["1", "1_1", "2", "2_1", "3", "3_1"]
arr.flat(); //["1", "1_1", "2", "2_1", Array(2)]

不限层级的嵌套

function flatDeep(arr, d = 1) {
  return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d -1) : val), []) : arr.slice();
}

function flatten2(array) {
  return array.flat(Infinity);
}

你可能感兴趣的:(Vue源码分析,深入JavaScript原理)