JavaScript Array.includes() 方法与数组一起使用,以检查数组中是否存在特定元素。它返回一个布尔值作为结果:如果在数组中找到 thr 元素,则返回 “true”,如果不存在,则返回 “false”。此方法对字符串和对象引用检查区分大小写。
如果我们为此方法提供负数 “fromIndex”,则搜索将从 backwards 开始。例如,-1 表示最后一个元素。
语法
以下是 JavaScript Array.includes() 方法的语法 -
array.includes(searchElement, fromIndex);
参数
此方法接受两个参数。下面将介绍相同的内容。
- searchElement - 您在数组中搜索的元素。
- fromIndex − 数组中要从中开始搜索的索引。如果未指定,则搜索从数组的开头开始。
返回值
如果在数组中找到搜索元素,则此方法返回 “true”,否则返回 “false”。
示例 1
在下面的示例中,我们使用 JavaScript Array.includes() 方法在指定数组中搜索元素 “Dinosaur”。
<html>
<body>
<p id="demo"></p>
<script>
const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"]
let result = animals.includes("Dinosaur");
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
输出
执行程序后,includes() 方法返回 “true”,因为元素 “Dinosaur” 存在于指定的数组中。
true
示例 2
在下面的示例中,我们在指定数组中搜索元素 “Wolf” -
<html>
<body>
<p id="demo"></p>
<script>
const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"]
let result = animals.includes("Wolf");
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
输出
执行程序后,includes() 方法返回 “false”,因为元素 “Dinosaur” 不存在于指定的数组中。
false
示例 3
在这里,我们检查指定的数组是否包含元素 “Elephant”,从索引位置 2 开始 -
<html>
<body>
<p id="demo"></p>
<script>
const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"]
let result = animals.includes("Elephant", 2);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
输出
程序返回 “true”,因为元素 “Elephant” 出现在索引位置 2 之后。
true
示例 4
在这里,我们检查指定的数组是否包含元素 “Cheetah”,从索引位置 3 开始 -
<html>
<body>
<p id="demo"></p>
<script>
const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"]
let result = animals.includes("Cheetah", 3);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
输出
程序返回 “false”,因为元素 “Cheetah” 出现在索引位置 3 之后。
false