// 示例代码:使用 Array.indexOf 方法
// 定义一个数组
const fruits = ['苹果', '香蕉', '橙子', '葡萄'];
// 查找元素在数组中的索引位置
const index = fruits.indexOf('橙子');
// 输出结果
console.log(index); // 输出: 2
// 如果查找的元素不存在于数组中,返回 -1
const notFoundIndex = fruits.indexOf('草莓');
console.log(notFoundIndex); // 输出: -1
Array.indexOf()
方法用于返回数组中某个指定元素的第一个索引,如果不存在,则返回 -1
。fruits.indexOf('橙子')
返回 2
,因为 '橙子'
在数组中的索引是 2
(从 0
开始计数)。'草莓'
时,由于它不在数组中,所以返回 -1
。上一篇:js tojson
下一篇:js 对象转map
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站