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

js indexof 用法

作者:硝烟   发布日期:2026-04-23   浏览:5

// 示例代码:使用 indexOf 方法查找数组或字符串中某个元素或子字符串的位置

// 数组中的用法
const array = [1, 2, 3, 4, 5];
const indexInArray = array.indexOf(3); // 返回 2,因为 3 在数组中的索引是 2
console.log(indexInArray);

// 字符串中的用法
const str = "Hello, world!";
const indexInString = str.indexOf("world"); // 返回 7,因为 "world" 在字符串中的起始索引是 7
console.log(indexInString);

// 如果没有找到元素或子字符串,则返回 -1
const notFoundIndex = array.indexOf(6); // 返回 -1,因为 6 不在数组中
console.log(notFoundIndex);

解释说明:

  • indexOf 方法用于查找指定元素(对于数组)或子字符串(对于字符串)在数组或字符串中首次出现的位置。
  • 如果找到了该元素或子字符串,则返回其索引;如果没有找到,则返回 -1

上一篇:js 数组 indexof

下一篇:js strip

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

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

Laravel 中文站