手写系列-Array-手写concat

434 阅读1分钟

数组的concat方法 arr.concat(arr1,arr2,arr3....) 连接多个数组 返回新的数组,不改变原数组

1.通过for循环

Array.prototype.myConcat = function () {
  //深度拷贝this
  //let arr = JSON.parse(JSON.stringify(this))
  let arr = [...this]
  for (let i = 0; i < arguments.length; i++) {
    if (Array.isArray(arguments[i])) {
      for (let j = 0; j < arguments[i].length; j++) {
        arr.push(arguments[i][j])
      }
    } else {
      arr.push(arguments[i])
    }
  }
  return arr
}

console.log([1, 2].myConcat([1, 2], [4, 5, 9], 9, 8))

输出结果[ 1, 2, 1, 2, 4, 5, 9, 9, 8 ]

2.通过forEach

Array.prototype.myConcat = function () {
  //let arr = JSON.parse(JSON.stringify(this))
  let arr = [...this]
  arguments = [...arguments]
  arguments.forEach(item => {
    Array.isArray(item) ? item.forEach(x => arr.push(x)) : arr.push(item)
  })
  return arr
}

const newArr = [1, 2].myConcat([1, 2], [4, 5, 9],7,5,6)

console.log(newArr) 

输出结果[ 1, 2, 1, 2, 4, 5, 9, 7, 5, 6 ]