Array.prototype.includes()

Baseline 已广泛支持

此功能已相当成熟,可在多种设备和浏览器版本上运行。自 ⁨2016 年 8 月⁩ 起,所有浏览器均已提供此功能。

includes() 方法 Array 实例用于确定数组是否包含某个值,如果包含则返回 true,否则返回 false

试一试

const array = [1, 2, 3];

console.log(array.includes(2));
// Expected output: true

const pets = ["cat", "dog", "bat"];

console.log(pets.includes("cat"));
// Expected output: true

console.log(pets.includes("at"));
// Expected output: false

语法

js
includes(searchElement)
includes(searchElement, fromIndex)

参数

searchElement

要搜索的值。

fromIndex 可选

开始搜索的基于零的索引,转换为整数

  • 负数索引从数组末尾开始计数 — 如果 -array.length <= fromIndex < 0,则使用 fromIndex + array.length。但是,在这种情况下,数组仍将从前到后进行搜索。
  • 如果 fromIndex < -array.length 或省略了 fromIndex,则使用 0,这将搜索整个数组。
  • 如果 fromIndex >= array.length,则不搜索数组并返回 false

返回值

一个布尔值,如果值 searchElement 在数组中(或在指定的 fromIndex 所指示的数组部分)找到,则为 true

描述

includes() 方法使用 SameValueZero 算法将 searchElement 与数组元素进行比较。零值无论符号如何都被视为相等。(即,-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); // false

fromIndex 大于或等于数组长度

如果 fromIndex 大于或等于数组的长度,则返回 false。不会搜索数组。

js
const arr = ["a", "b", "c"];

arr.includes("c", 3); // false
arr.includes("c", 100); // false

计算出的索引小于 0

如果 fromIndex 为负数,则计算出的索引将被用作数组中开始搜索 searchElement 的位置。如果计算出的索引小于或等于 0,则会搜索整个数组。

js
// array length is 3
// fromIndex is -100
// computed index is 3 + (-100) = -97

const arr = ["a", "b", "c"];

arr.includes("a", -100); // true
arr.includes("b", -100); // true
arr.includes("c", -100); // true
arr.includes("a", -2); // false

在稀疏数组上使用 includes()

您可以在稀疏数组中搜索 undefined 并获得 true

js
console.log([1, , 3].includes(undefined)); // true

在非数组对象上调用 includes()

includes() 方法读取 thislength 属性,然后访问其键为小于 length 的非负整数的每个属性。

js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 1, // ignored by includes() since length is 3
};
console.log(Array.prototype.includes.call(arrayLike, 2));
// true
console.log(Array.prototype.includes.call(arrayLike, 1));
// false

规范

规范
ECMAScript® 2026 语言规范
# sec-array.prototype.includes

浏览器兼容性

另见