在前端开发领域中,JavaScript 是不可或缺的一门语言。除了基本语法和数据类型的掌握,熟练掌握 JavaScript 中的各种函数和方法也是必不可少的。在这些方法中,Array.prototype.includes 是一个非常常用且方便的用于数组查找的方法。在此,我们探讨如何手动实现 ES7 的 Array.prototype.includes。
理解 Array.prototype.includes 的作用
Array.prototype.includes 的作用是用来查找数组中是否包含某个元素。它返回一个布尔值以表示是否找到了该元素。举个例子:
const arr = [1, 2, 3, 4]; console.log(arr.includes(2)); // true console.log(arr.includes(5)); // false
实现步骤
接下来我们将逐步实现 Array.prototype.includes 方法。
第一步:获取数组长度
由于我们需要遍历整个数组,因此需要获取数组的长度。因此,我们先实现获取数组长度的方法。
Array.prototype.myIncludes = function (searchElement, fromIndex) {
const { length } = this;
// ... 接下来的代码中会用到 length 变量
};第二步:判断查找起始位置
根据 Array.prototype.includes 的定义,第二个参数可选,用于指定查找的起始位置。如果未指定,就从数组开头开始查找。
我们可以通过判断 fromIndex 是否存在,若不存在则默认为 0,从第一个元素开始查找。
Array.prototype.myIncludes = function (searchElement, fromIndex = 0) {
const { length } = this;
let startIndex = fromIndex >= 0 ? fromIndex : length + fromIndex;
// ... 接下来的代码中会用到 startIndex 变量
};第三步:遍历数组
我们通过 for 循环遍历数组,将每个元素和查找的元素进行比较。如果相等,就返回 true。需要注意的是,我们需要特别处理一些特殊值,如 NaN。
-- -------------------- ---- -------
-------------------------- - -------- --------------- --------- - -- -
----- - ------ - - -----
--- ---------- - --------- -- - - --------- - ------ - ----------
--- ---- - - ----------- - - ------- ---- -
----- ------- - --------
-- -------------- --- ------------- -- ------- --- -------- -
-- ------------- --- ---------
------ -----
-
-- -------- --- -------------- -
------ -----
-
-
------ ------
--第四步:完成实现
现在,我们已经完成了 Array.prototype.includes 方法的手动实现。下面是完整代码:
-- -------------------- ---- -------
-------------------------- - -------- --------------- --------- - -- -
----- - ------ - - -----
--- ---------- - --------- -- - - --------- - ------ - ----------
--- ---- - - ----------- - - ------- ---- -
----- ------- - --------
-- -------------- --- ------------- -- ------- --- -------- -
-- ------------- --- ---------
------ -----
-
-- -------- --- -------------- -
------ -----
-
-
------ ------
--思考题
到这里,我们已经成功地手动实现了 Array.prototype.includes 方法。但是,我们在实现过程中也遇到了一些问题,如何处理 NaN 等特殊情况。
这些问题告诉我们,在开发过程中,我们需要考虑到各种情况,否则可能会留下一些不易被察觉的漏洞。在编写代码时,我们也需要注意不要依赖于语言本身的特性,而要寻求能够跨浏览器平台工作的解决方案。
结语
本文详细介绍了手动实现 ES7 的 Array.prototype.includes 方法的过程。此外,我们在实现过程中也学到了一些解决特殊情况的方法,这对于我们编写健壮的 JavaScript 代码是非常有帮助的。为了更好地应对面试中可能出现的问题,我们建议大家将此方法手动实现一次,加深对 JavaScript 数组方法的理解。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/67cd9ba4e46428fe9e7380c1