当前位置:首页 > 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 上下文。

js 实现 find 方法

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

边界条件处理

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

js 实现 find 方法

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)。

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实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-containe…

原生js实现轮播图

原生js实现轮播图

基本结构搭建 HTML部分需要包含轮播图容器、图片列表及导航按钮。结构示例如下: <div class="slider-container"> <div class="slid…

js实现复制到剪贴板

js实现复制到剪贴板

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

js实现图表

js实现图表

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

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…