数组 concat

177 阅读1分钟

起因是实现数组展开一层

  1. concat和...扩展符实现;
  2. concat apply实现;

concat实现,函数不会修改原有数组

const res = [1, [2, 3]];
console.log([].concat.apply([], res));
console.log([].concat(...res));

Array.prototype.myConcat = function () {
  const merge = [];
  //concat 不修改现有数组
  for (let i = 0; i < this.length; i++) {
    //a数组调用concat, 所以this指向a数组
    merge.push(this[i]);
  }
  for (let j = 0; j < arguments.length; j++) {
    const args = arguments[j];
    //判断参数是不是数组
    if (args instanceof Array) {
      for (let k = 0; k < args.length; k++) {
        merge.push(args[k]);
      }
    } else {
      merge.push(args);
    }
  }
  return merge;
};

const a = [1, 2, 3],
  b = [3, 4, 5];
const c = [1, 2, 3],
  d = [3, [4, 5]];
const e = [1, [2, 3]],
  f = [3, [4, 5]];
console.log(a.myConcat(b)); // [1, 2, 3, 3, 4, 5]
console.log(c.myConcat(d)); // [1, 2, 3, 3, [4, 5]]
console.log(e.myConcat(f)); // [1, [2, 3], 3, [4, 5]]
console.log(e.myConcat(...f)); // [1, [2, 3], 3, 4, 5]

涉及到apply,想见call,apply章节