在 ES7 中,新增了一个 Array.prototype.includes 方法,用于判断数组中是否包含某个元素,返回值为布尔类型。那么这个方法是如何实现的呢?本文将探究这个方法的实现本质,并深入学习和指导意义。
实现本质
我们首先来看一下 Array.prototype.includes 方法的语法:
Array.prototype.includes(searchElement[, fromIndex])
其中,searchElement 表示要查找的元素,fromIndex 表示开始查找的位置,可选参数,默认值为 0。
我们可以通过以下的方式来手动实现这个方法:
Array.prototype.myIncludes = function(searchElement, fromIndex = 0) { for (let i = fromIndex; i < this.length; i++) { if (this[i] === searchElement) { return true; } } return false; }
我们通过循环遍历数组,从指定位置开始寻找要查找的元素,如果找到了就返回 true,否则返回 false。
那么在 Array.prototype.includes 的实现中,又是如何实现的呢?实现方法如下:
Array.prototype.includes = function(searchElement, fromIndex = 0) { return this.indexOf(searchElement, fromIndex) !== -1; }
我们可以看到,在 Array.prototype.includes 方法中,直接调用了数组的 indexOf 方法,如果查找成功,就返回 true,否则返回 false。通过这种方式我们不仅可以利用数组原生的 indexOf 方法,避免手写循环带来的性能问题,还可以在查找没有找到的情况下,少执行一次循环。这就是 Array.prototype.includes 方法的实现本质。
学习和指导意义
了解了 Array.prototype.includes 方法的实现本质,我们可以来看一下学习和指导意义。
学习意义
通过了解 Array.prototype.includes 方法的实现本质,我们不仅可以更加深入地了解这个方法的底层实现,还可以通过手动实现这个方法,提升我们对 JavaScript 的编程能力。另外,我们还可以借鉴这种方式,在日常开发过程中使用原生方法,提高代码的执行效率,并避免因为代码逻辑出错而引入的 bug。
指导意义
对于前端开发者来说,熟悉 ES7 的特性并能够灵活地运用,可以提高我们开发的效率和质量。同时,我们也应该注意到在 ES7 中新增的一些特性,可能并不被所有浏览器兼容,因此在使用过程中需要注意特性是否兼容。
在日常开发过程中,我们也可以借鉴这种 Array.prototype.includes 方法的实现方式,在代码层面上,提高代码执行效率,减少循环的执行时间,减少代码的 bug 概率。
示例代码
最后,我们来看一下如何使用 Array.prototype.includes 方法,如下:
const array = [1, 2, 3, 4, 5]; console.log(array.includes(3)); // 输出结果为:true console.log(array.includes(6)); // 输出结果为:false
如果您的浏览器不支持 ES7,则需要手动实现 Array.prototype.includes 方法,如下:
-- -------------------- ---- ------- -------------------------- - ----------------------- --------- - -- - --- ---- - - ---------- - - ------------ ---- - -- -------- --- -------------- - ------ ----- - - ------ ------ - ----- ----- - --- -- -- -- --- --------------------------------- -- ---------- --------------------------------- -- -----------展开代码
通过这种方式,我们可以在不支持 ES7 的浏览器中,手动实现 Array.prototype.includes 方法,以达到与使用原生方法相同的效果。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67c438196e1fc40e36d1cc17