手写系列-Array-手写every,some

406 阅读1分钟

手写every

every为数组方法, 有两个参数,cb和thisValue,每个元素都满足条件则返回true,有一个不满足就返回false且停止向下遍历

Array.prototype.myEvery = function (cb, thisvalue) {
  //当接收参数不为方法时 抛出异常
  if (typeof cb !== "function") throw new Error('该方法接收回调函数')
  let arr = []
  //获取this值
  thisvalue === undefined ? arr = [...this] : arr = [...thisvalue]
  let flag = true
  for (let i = 0; i < arr.length; i++) {
    if (!cb(arr[i], i, arr)) return flag = false
  }
  return flag
}

const arr = [13]
console.log(arr.myEvery((item) => item > 15, [12, 15, 45]))

输出结果false

手写some

some为数组方法,参数为cb和thisValue,只要有一个满足条件就返回true,停止向下遍历.所有都不满足返回false

Array.prototype.mySome = function (cb, thisValue) {
  if (typeof cb !== 'function') throw new Error('接收参数为函数')
  let arr = []
  thisValue ? arr = [...thisValue] : arr = [...this]
  let flag = false
  for (let i = 0; i < arr.length; i++) {
    if (cb(arr[i], i, arr)) return flag = true
  }
  return flag
}

const arr = [2, 3]

console.log(arr.mySome((item) => item < 3, [5]))

输出结果false