Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js includes和indexof

作者:淡漠伤悲   发布日期:2025-08-03   浏览:43

// 使用 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() 方法用于检查字符串或数组中是否包含指定的子字符串或元素,返回布尔值(truefalse)。
  • indexOf() 方法用于查找字符串或数组中指定子字符串或元素的位置,返回其首次出现的索引位置。如果未找到,则返回 -1

以上代码展示了如何在字符串和数组中使用这两个方法。

上一篇:nodejs typescript

下一篇:js assert

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 点击空白区域触发事件

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站