此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Array.prototype.includes()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2016年8月.
includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回true,否则返回false。
In this article
尝试一下
const array1 = [1, 2, 3];console.log(array1.includes(2));// Expected output: trueconst pets = ["cat", "dog", "bat"];console.log(pets.includes("cat"));// Expected output: trueconsole.log(pets.includes("at"));// Expected output: false语法
js
includes(searchElement)includes(searchElement, fromIndex)参数
searchElement需要查找的值。
fromIndex可选开始搜索的索引(从零开始),会转换为整数。
- 负索引从数组末尾开始计数——如果
fromIndex < 0,那么实际使用的是fromIndex + array.length。然而在这种情况下,数组仍然从前往后进行搜索。 - 如果
fromIndex < -array.length或者省略fromIndex,则使用0,这将导致整个数组被搜索。 - 如果
fromIndex >= array.length,则不会搜索数组并返回false。
- 负索引从数组末尾开始计数——如果
返回值
一个布尔值,如果在数组中(或者在fromIndex 所指示的数组部分中,如果指定fromIndex 的话)找到searchElement 值,则该值为true。
描述
includes() 方法使用零值相等算法将searchElement 与数组中的元素进行比较。0 值都被认为是相等的,不管符号是什么。(即-0 等于0),但false不被认为与0 相同。NaN 可以被正确搜索到。
当在稀疏数组上使用时,includes() 方法迭代空槽,就像它们的值是undefined 一样。
includes() 方法是通用的。它只期望this 值具有length 属性和整数键属性。
示例
>使用 includes() 方法
js
[1, 2, 3].includes(2); // true[1, 2, 3].includes(4); // false[1, 2, 3].includes(3, 3); // false[1, 2, 3].includes(3, -1); // true[1, 2, NaN].includes(NaN); // true["1", "2", "3"].includes(3); // falsefromIndex 大于等于数组长度
如果fromIndex 大于等于数组的长度,则将直接返回false,且不搜索该数组。
js
const arr = ["a", "b", "c"];arr.includes("c", 3); // falsearr.includes("c", 100); // false计算出的索引小于 0
如果fromIndex 为负值,计算出的索引将作为开始搜索searchElement 的位置。如果计算出的索引小于0,则整个数组都会被搜索。
js
// 数组长度为 3// fromIndex 为 -100// 计算出的索引为 3 + (-100) = -97const arr = ["a", "b", "c"];arr.includes("a", -100); // truearr.includes("b", -100); // truearr.includes("c", -100); // truearr.includes("a", -2); // false对稀疏数组使用 includes() 方法
你可以在稀疏数组中搜索undefined,得到true 。
js
console.log([1, , 3].includes(undefined)); // true在非数组对象上调用 includes() 方法
includes() 方法读取this 的length 属性,然后访问每个整数索引。
js
const arrayLike = { length: 3, 0: 2, 1: 3, 2: 4,};console.log(Array.prototype.includes.call(arrayLike, 2));// trueconsole.log(Array.prototype.includes.call(arrayLike, 1));// false规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-array.prototype.includes> |