// 示例代码:使用 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
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站