day6:js数组方法find、findIndex、lastIndexOf的实现

148 阅读1分钟

js数组方法find的实现逻辑:

  const arr = [1, 2, 3];

  Array.prototype._find = function (cb) {
    if (typeof cb !== 'function') {
      throw new Error('cb is not a function');
    }
    const arr = [...this];
    let i = 0;
    const len = arr.length;
    let cur = void 0;
    while (i < len) {
      const condition = cb(arr[i], i, arr);
      if (condition) {
        cur = arr[i];
        break
      }
      i++
    }
    return cur;
  }
  console.log(arr._find(v => v % 2 === 0));
  // 输出结果: 2

js数组方法findIndex的实现逻辑:

const arr = [1, 2, 3]

Array.prototype._findIndex = function (cb) {
  if (typeof cb !== 'function') {
    throw new Error('cb is not a function');
  }
  const arr = [...this];
  let i = 0;
  const len = arr.length;
  let curIndex = -1;
  while (i < len) {
    const condition = cb(arr[i], i, arr);
    if (condition) {
      curIndex = i;
      break
    }
    i++
  }
  return curIndex;
}
console.log(arr._findIndex(v => v % 2 === 0));
// 输出结果: 1

js数组方法indexOf的实现逻辑:

const arr = [1, 2, 3]
Array.prototype._indexOf = function (val) {
  let i = 0,
      index = -1;
  const len = this.length;
  while (i < len) {
    if (this[i] === val)
      index = i;
      break;
      i++
  }
  return index;
}
console.log(arr._indexOf(1))
// 输出结果:0

js数组方法lastIndexOf的实现逻辑:

const arr = [1, 2, 2, 2, 5, 3]
Array.prototype._lastIndexOf = function (val, lastIndex) {
  if (lastIndex ?? lastIndex) {
    lastIndex *= 1;
    if (isNaN(lastIndex * 1)) {
      throw new Error('lastIndex is not a valid number')
    }
  }
  let len = this.length - 1;
  if (!this.length) {
    len = 0;
  } else {
    if (lastIndex < len) {
      if (lastIndex < 0) {
        const curIndex = this.length - lastIndex * -1;
        len = curIndex
      }
    }
  }
  let index = -1;
  for (let i = len; i >= 0; i--) {
    if (val === this[i]) {
      index = i;
      break;
    }
  };
  return index;
}
console.log(arr._lastIndexOf(3))
// 输出结果:5