// 示例代码:使用 indexOf 方法查找数组或字符串中某个元素的索引位置
// 数组示例
const fruits = ['apple', 'banana', 'orange', 'grape'];
const indexInArray = fruits.indexOf('orange');
console.log(indexInArray); // 输出: 2,表示 'orange' 在数组中的索引是 2
// 字符串示例
const str = "Hello, world!";
const indexInString = str.indexOf('world');
console.log(indexInString); // 输出: 7,表示 'world' 在字符串中的起始索引是 7
// 如果没有找到元素,indexOf 返回 -1
const notFoundIndex = fruits.indexOf('watermelon');
console.log(notFoundIndex); // 输出: -1,表示 'watermelon' 不在数组中
上一篇:js trycatch
下一篇:js self
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站