// 使用 includes 和 indexOf 的示例
// 定义一个字符串
let str = "Hello, world!";
// 使用 includes 检查字符串中是否包含某个子字符串
if (str.includes("world")) {
console.log("字符串中包含 'world'。");
}
// 使用 indexOf 查找子字符串的位置
let index = str.indexOf("world");
if (index !== -1) {
console.log("子字符串 'world' 位于索引 " + index + " 处。");
}
// 定义一个数组
let arr = [1, 2, 3, 4, 5];
// 使用 includes 检查数组中是否包含某个元素
if (arr.includes(3)) {
console.log("数组中包含数字 3。");
}
// 使用 indexOf 查找数组中元素的位置
let arrIndex = arr.indexOf(3);
if (arrIndex !== -1) {
console.log("数字 3 位于数组索引 " + arrIndex + " 处。");
}
includes()
方法用于检查字符串或数组中是否包含指定的子字符串或元素,返回布尔值(true
或 false
)。indexOf()
方法用于查找字符串或数组中指定子字符串或元素的位置,返回其首次出现的索引位置。如果未找到,则返回 -1
。以上代码展示了如何在字符串和数组中使用这两个方法。
下一篇:js assert
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站