当前位置:首页 > JavaScript

js 实现 find 方法

2026-02-03 00:11:22JavaScript

实现基础数组查找功能

通过回调函数匹配数组元素,返回第一个满足条件的元素。若未找到则返回 undefined

Array.prototype.customFind = function(callback) {
  for (let i = 0; i < this.length; i++) {
    if (callback(this[i], i, this)) {
      return this[i];
    }
  }
  return undefined;
};

使用示例

const numbers = [1, 2, 3, 4];
const found = numbers.customFind(item => item > 2);
console.log(found); // 输出: 3

支持 thisArg 参数

允许通过 thisArg 指定回调函数的 this 上下文。

Array.prototype.customFind = function(callback, thisArg) {
  const context = thisArg || undefined;
  for (let i = 0; i < this.length; i++) {
    if (callback.call(context, this[i], i, this)) {
      return this[i];
    }
  }
  return undefined;
};

使用示例

const obj = { threshold: 2 };
const found = [1, 2, 3].customFind(
  function(item) { return item > this.threshold; },
  obj
);
console.log(found); // 输出: 3

边界条件处理

增加对稀疏数组和非法回调的校验,提升健壮性。

Array.prototype.customFind = function(callback, thisArg) {
  if (typeof callback !== 'function') {
    throw new TypeError('Callback must be a function');
  }
  const context = thisArg || undefined;
  for (let i = 0; i < this.length; i++) {
    if (i in this && callback.call(context, this[i], i, this)) {
      return this[i];
    }
  }
  return undefined;
};

校验场景

// 稀疏数组
const sparse = [1, , 3];
console.log(sparse.customFind(item => item === undefined)); // undefined  

// 非法回调
try {
  [1, 2].customFind(null);
} catch (e) {
  console.log(e.message); // "Callback must be a function"
}

性能优化建议

对于大型数组,可考虑提前终止循环或使用更高效的遍历方式(如 for-of)。

js 实现 find 方法

Array.prototype.customFind = function(callback, thisArg) {
  const context = thisArg || undefined;
  for (const [index, value] of this.entries()) {
    if (callback.call(context, value, index, this)) {
      return value;
    }
  }
  return undefined;
};

标签: 方法js
分享给朋友:

相关文章

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js实现报表

js实现报表

使用JavaScript实现报表 在JavaScript中实现报表功能可以通过多种方式完成,常见的方法包括使用原生JavaScript、第三方库(如Chart.js、D3.js)或结合后端数据渲染。以…

base64转换方法uniapp

base64转换方法uniapp

Base64 转换方法(UniApp) 在 UniApp 中实现 Base64 编码和解码,可以通过原生 JavaScript 的 btoa 和 atob 方法,或使用第三方库如 base64-js。…

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数: fun…

js实现路由

js实现路由

js实现路由的方法 在JavaScript中实现路由功能可以通过多种方式完成,以下是几种常见的方法: 使用原生JavaScript实现路由 通过监听window.onhashchange事件来实现基…