JavaScript 中的 includes() 方法用于检查数组或字符串中是否包含特定的元素或子字符串。根据指定的 start 参数,它从字符串或数组中的特定位置开始查找。如果找到,则返回 true;如果没有找到,则返回 false。

JavaScript 中 includes() 用法
什么是 includes()?
includes() 是 JavaScript 中一个内置方法,它用于判断一个字符串或数组是否包含给定的子字符串或元素。
语法
<code class="javascript">array.includes(element, start) string.includes(substring, start)</code>
其中:
array 或 string:要检查的数组或字符串。element 或 substring:要在其中查找的元素或子字符串。start(可选):指定从字符串或数组中的哪个位置开始查找(从 0 开始)。用法
数组
要检查数组中是否包含某个元素,可以使用以下语法:
<code class="javascript">const fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("apple")); // true
console.log(fruits.includes("grape")); // false</code>字符串
要检查字符串中是否包含某个子字符串,可以使用以下语法:
<code class="javascript">const message = "Hello, world!";
console.log(message.includes("world")); // true
console.log(message.includes("universe")); // false</code>可选的 start 参数
start 参数允许您指定从字符串或数组中的哪个位置开始查找。例如:
<code class="javascript">const fruits = ["apple", "banana", "orange", "apple"];
console.log(fruits.includes("apple", 2)); // true (从索引 2 开始查找)
console.log(message.includes("world", 6)); // false (从索引 6 开始查找)</code>返回结果
includes() 方法返回一个布尔值:
true:如果找到了指定的元素或子字符串。false:如果找不到指定的元素或子字符串。以上就是js中includes用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号