JavaScript includes 方法
最后修改于 2025 年 4 月 4 日
在本文中,我们将展示如何使用 JavaScript 中的 includes
方法检查元素。
使用 includes 进行元素检查
includes
方法确定数组或字符串是否包含指定的元素或子字符串。如果找到则返回 true
,否则返回 false
。此方法执行区分大小写的搜索。
对于数组,它检查是否有任何元素与搜索元素匹配。对于字符串,它检查是否存在子字符串匹配。该方法接受一个可选的第二个参数来指定搜索的起始位置。
当您只需要一个布尔结果时,includes
方法对于简单的存在性检查很有用,而不需要索引位置。 与 indexOf
相比,它提供了一个更具可读性的替代方案。
基本数组 includes 示例
以下示例演示了如何检查数组中的元素。
const fruits = ['apple', 'banana', 'orange']; const hasBanana = fruits.includes('banana'); const hasMango = fruits.includes('mango'); console.log(hasBanana); console.log(hasMango);
我们检查“banana”和“mango”是否存在于 fruits 数组中。该方法对数组中存在的元素返回 true
,对未找到的元素返回 false
。搜索是区分大小写的。
$ node main.js true false
字符串 includes 示例
includes
方法也可以检查字符串中的子字符串。
const sentence = 'The quick brown fox jumps over the lazy dog'; const hasFox = sentence.includes('fox'); const hasCat = sentence.includes('cat'); console.log(hasFox); console.log(hasCat);
我们检查句子是否包含“fox”和“cat”子字符串。该方法对字符串的处理方式与对数组的处理方式类似。默认情况下,字符串搜索也区分大小写。
$ node main.js true false
includes 中的大小写敏感性
默认情况下,includes
方法执行区分大小写的搜索。
const colors = ['Red', 'Green', 'Blue']; const hasRed = colors.includes('red'); const hasGreen = colors.includes('Green'); console.log(hasRed); console.log(hasGreen);
我们演示了 includes
方法的大小写敏感性。对“red”的搜索失败,因为数组包含带有大写 R 的“Red”。成功的搜索需要匹配大小写。
$ node main.js false true
使用位置参数
可选的第二个参数指定搜索的起始位置。
const numbers = [1, 2, 3, 4, 5, 2]; const hasTwoAtStart = numbers.includes(2); const hasTwoAfterPos3 = numbers.includes(2, 3); console.log(hasTwoAtStart); console.log(hasTwoAfterPos3);
我们从不同的位置搜索数字 2。第一次搜索找到第一次出现。第二次搜索从位置 3 开始,找到第二次出现。负位置从数组的末尾开始计数。
$ node main.js true true
使用 includes 检查 NaN
includes
方法可以正确识别 NaN
值。
const values = [1, NaN, 3]; const hasNaN = values.includes(NaN); const indexOfNaN = values.indexOf(NaN); console.log(hasNaN); console.log(indexOfNaN);
与 indexOf
不同,includes
可以正确检测数组中的 NaN
值。这是因为 includes
使用 SameValueZero 算法,该算法将 NaN
视为等于自身。
$ node main.js true -1
来源
在本文中,我们演示了如何使用 includes() 方法检查 JavaScript 中数组和字符串中的元素。
作者
列出 所有 JS 数组函数。