Array.prototype.includes 是 JavaScript 中的一种用于检查数组中是否包含指定元素的方法,可在 ES7 中使用。它返回一个布尔值,表示数组中是否包含该元素,并且可以通过数组的索引来查找元素。
在实际开发中,我们经常需要使用 Array.prototype.includes 来查找数组中是否存在某个元素。鉴于该方法的重要性,本文将会深入探讨 Array.prototype.includes 方法的性能优化以及如何在开发中更好地使用。
原理介绍
ES7 标准中包含一个 Array.prototype.includes 方法,它用于检查数组中是否包含一个特定的元素。不像 indexOf 方法,它支持在查找时处理 NaN 值,并使用 "===" 运算符进行查找。
其语法结构为:
arr.includes(valueToFind[, fromIndex])
其中 arr 是要查找的数组,valueToFind 是要查找的元素,fromIndex 是可选参数,从数组的哪个位置开始查找元素。
性能优化
在实际开发中,由于数组的长度可能非常巨大,因此我们需要对性能进行优化,避免出现性能问题。以下是一些性能优化的方法:
1. 避免多次循环搜索
在实现 Array.prototype.includes 方法时,避免使用多次循环搜索同一个元素。这样会导致性能问题。
下面代码演示了单次搜索和多次搜索的比较:
// www.javascriptcn.com code example
const myArr = [1, 2, 3, 4, 5];
const myValue = 3;
// 每次循环开始搜索
let isPresent = false;
for(let i=0; i<myArr.length; i++){
if(myArr[i] === myValue){
isPresent = true;
break;
}
}
console.log(isPresent); // true
// 先进行一次数组搜索
const allValues = [...myArr];
const isPresent2 = allValues.includes(myValue);
console.log(isPresent2); // true2. 使用 Set 对象
Set 对象是 JavaScript ES6 的新特性之一,它可以存储大量数据,而不会出现重复项。由于包含的成员是唯一的,因此在处理大量数据时,它可以大大提高性能。
以下代码演示了使用 Set 对象进行搜索的比较:
// www.javascriptcn.com code example
const myArr = [1, 2, 3, 4, 5];
const mySet = new Set(myArr);
const myValue = 3;
// 遍历 Set 进行搜索
let isPresent = false;
mySet.forEach((value) => {
if(value === myValue){
isPresent = true;
}
});
console.log(isPresent); // true
// 使用 Set 自带的 has 方法
const isPresent2 = mySet.has(myValue);
console.log(isPresent2); // true3. 索引的优化
在实现 Array.prototype.includes 方法时,我们可以检查 fromIndex 索引参数,并使用它来定位查找元素的起点。
// www.javascriptcn.com code example
Array.prototype.myIncludes = function(valueToFind, fromIndex = 0){
if (fromIndex < 0) {
fromIndex = this.length + fromIndex;
if (fromIndex < 0) {
fromIndex = 0;
}
}
for (var i = fromIndex, len = this.length; i < len; i++) {
var currentValue = this[i];
if (currentValue === valueToFind) {
return true;
}
}
return false;
}以上方法可以在实践中实现较高性能,更好地优化前端应用的性能表现。
指导意义
- 了解 Array.prototype.includes 方法的使用和原理
- 通过优化方式提高前端应用的性能表现
- 更好地使用 JavaScript 中的 Set 对象
示例代码
以下代码是利用 Sel 对象的性质实现的 Array.prototype.includes 方法的优化版本。
// www.javascriptcn.com code example
Array.prototype.myIncludes = function(valueToFind, fromIndex = 0){
if (fromIndex < 0) {
fromIndex = this.length + fromIndex;
if (fromIndex < 0) {
fromIndex = 0;
}
}
const mySet = new Set(this.slice(fromIndex));
return mySet.has(valueToFind);
}如上的代码实现了基于 Set 对象的性质,以及适当的执行判断机制,可能会对当前 Array.prototype.includes 方法,或其他相对应阵列检索函数提供一些方便,更快速地找到表格中目标想要的元素的内容。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67cfdd5ae46428fe9ec0e7e2