includes
includes 是 Array 和 String 的方法,用于检查数组或字符串是否包含指定的元素或子字符串。
查询数组内是否包含某个元素
let arr = [1, 2, 3, 4, 5];
console.log(arr.includes(1)); // true
在这个例子中,includes 方法用来检查数组是否包含元素 1,返回值为 true。
查询稀松数组
对于稀松数组(数组中有空位),可以使用 includes 查询是否包含 undefined。
let epy = [1, 2, ,];
console.log(epy.includes(void 0)); // true
注意,稀松数组中空位会被认为是 undefined,因此 includes 能正确识别。
查询字符串
includes 方法对于字符串也可以使用,并且会区分大小写。此外,它还区分字符数字和数字类型。
let str = '123123';
console.log(str.includes('1')); // true
在这个例子中,includes 用于检查字符串 '123123' 中是否包含字符 '1',返回值为 true。
参数
includes 方法接收两个参数:
- 检索的值
- 可选的开始的下标(默认为 0)
let str = '123123';
console.log(str.includes('123', 3)); // true
在上述代码中,查询从索引 3 开始,是否包含子字符串 '123',返回 true。
需要注意,includes 方法的 length 属性表示它的参数数量,在此情况下,length 的值为 1,因为 startIndex 是可选的。
let str = '123123';
console.log(str.includes.length); // 1
零值相等
includes 方法在比较数值时,遵循相等性规则,包括 +0 和 -0 视为相等。
var arr = [1, 2, 0];
console.log(arr.includes(0)); // true
console.log(arr.includes(-0)); // true
console.log(arr.includes(+0)); // true
这里的例子展示了 0、-0 和 +0 在数组中都会被视为相等。
类数组对象
includes 方法不仅适用于数组,还可以通过 call 或 apply 作用于类数组对象。
var obj = {
0: 1,
1: 2,
length: 2,
};
console.log([].includes.call(obj, 1)); // true
这里使用 call 方法将 includes 应用于一个类数组对象,从而检查该对象是否包含元素 1。
实现 includes 方法
下面是自定义实现 includes 方法的代码。它通过遍历数组并比较每个元素来检查是否包含指定的值。
Array.prototype.myIncludes = function (value) {
if (this == null) {
throw new TypeError('"this" is null or undefined');
}
var fromIndex = arguments[1];
var obj = Object(this);
var len = obj.length >>> 0; // 获取数组长度
if (len === 0) {
return false;
}
fromIndex = fromIndex | 0; // 将开始下标转为整数
// 确保从有效的索引开始查找
fromIndex = Math.max(fromIndex >= 0 ? fromIndex : len + fromIndex, 0);
while (fromIndex < len) {
if (obj[fromIndex] === value) {
return true;
}
fromIndex++;
}
return false;
};
let arr = [1, 2, 3, 4, 5];
console.log(arr.myIncludes(1)); // true
console.log(arr.myIncludes(1, -1)); // true
console.log(arr.myIncludes(1, -6)); // false
console.log(arr.myIncludes()); // false
关键步骤解析:
this == null用于检查this是否为null或undefined。- 使用
Object(this)将类数组对象转换为标准数组,避免一些边界问题。 fromIndex确保我们从一个有效的索引位置开始查找,如果提供了负值,它会从数组的末尾开始计算。- 通过
Math.max确保开始查找的索引不小于 0。 - 遍历数组并比较每个元素,找到匹配项时返回
true,否则继续查找。