Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
js 如何用indexOf查找数组中元素的索引_创想鸟

js 如何用indexOf查找数组中元素的索引

在javascript中查找数组元素索引最常用的方法是indexof(),它返回指定元素首次出现的索引,若未找到则返回-1;2. indexof()使用严格相等(===)比较,因此类型和值都必须匹配;3. 该方法可接受第二个参数fromindex,用于指定查找起始位置,若该值大于等于数组长度则直接返回-1;4. indexof()无法查找nan,因为nan不等于自身,此时应使用findindex()结合isnan()或includes()方法;5. 对于对象数组或复杂条件查找,应使用findindex(),因为它接受回调函数并可自定义匹配逻辑;6. 要查找某元素所有匹配的索引,需通过循环结合indexof()的fromindex参数反复查找,每次从上一个匹配位置的后一位开始;7. indexof()能正常查找undefined和null,但在处理特殊值和复杂数据结构时需注意其局限性。

js 如何用indexOf查找数组中元素的索引

在 JavaScript 里,要查找数组中元素的索引,最直接也最常用的方法就是使用数组自带的

indexOf()

方法。它会返回你要找的那个元素在数组里第一次出现的位置(也就是索引值),如果数组里根本没有这个元素,它就会给你返回

-1

解决方案

indexOf()

方法的用法其实挺简单的,它接受两个参数:你要查找的元素,以及一个可选的参数,表示从哪个索引位置开始查找。

它的基本语法是这样的:

arr.indexOf(searchElement[, fromIndex])
searchElement

:这是你想要在数组中查找的那个值。

fromIndex

(可选):一个整数,表示从数组的哪个索引位置开始向后查找。如果你省略了这个参数,或者给它传了个小于 0 的值,查找就会从数组的开头(索引 0)开始。如果传的值大于或等于数组的长度,那么

indexOf

就不会执行任何搜索,直接返回

-1

让我们看几个例子,这会让你对它的行为模式有个更清晰的认识:

const fruits = ['apple', 'banana', 'orange', 'apple', 'grape'];// 查找 'banana' 的索引const bananaIndex = fruits.indexOf('banana');console.log(bananaIndex); // 输出: 1// 查找 'apple' 的索引,注意它只返回第一个匹配的const firstAppleIndex = fruits.indexOf('apple');console.log(firstAppleIndex); // 输出: 0// 查找一个不存在的元素const kiwiIndex = fruits.indexOf('kiwi');console.log(kiwiIndex); // 输出: -1// 从特定索引开始查找// 查找从索引 2('orange')开始的 'apple'const secondAppleIndex = fruits.indexOf('apple', 2);console.log(secondAppleIndex); // 输出: 3// 数组中没有的元素,即使指定了起始索引也一样const noSuchElement = fruits.indexOf('mango', 0);console.log(noSuchElement); // 输出: -1// fromIndex 大于等于数组长度,直接返回 -1const fromTooFar = fruits.indexOf('apple', 10);console.log(fromTooFar); // 输出: -1
indexOf()

在查找时使用的是严格相等(

===

)比较。这意味着它不仅比较值,还会比较类型。比如,数字

5

和字符串

'5'

indexOf()

看来是完全不同的。

const mixedArray = [1, '2', 3, '4'];console.log(mixedArray.indexOf(1));   // 输出: 0console.log(mixedArray.indexOf('2'));  // 输出: 1console.log(mixedArray.indexOf(2));    // 输出: -1 (数字 2 不存在,只有字符串 '2')

indexOf 和 findIndex 有什么区别

这是个经常被问到的问题,因为它们听起来功能很相似,但实际应用场景却大相径庭。简单来说,

indexOf

专注于查找值的索引,而

findIndex

则专注于查找满足某个条件的元素的索引

indexOf()

: 就像我们上面说的,它用严格相等 (

===

) 来比较你提供的

searchElement

和数组中的每一个元素。它最适合用来查找原始类型(字符串、数字、布尔值、

null

undefined

)在数组中的位置。它无法直接用来查找对象或数组(除非它们是同一个内存地址的引用)。

const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];const targetUser = { id: 1, name: 'Alice' };// 这会返回 -1,因为 targetUser 和数组中的第一个对象虽然内容一样,但不是同一个对象引用console.log(users.indexOf(targetUser)); // 输出: -1

findIndex()

: 这个方法强大得多,因为它接受一个回调函数作为参数。这个回调函数会为数组中的每个元素执行一次,当回调函数返回

true

时,

findIndex

就会返回当前元素的索引,然后停止遍历。如果没有任何元素让回调函数返回

true

,它就返回

-1

。这让

findIndex

在处理复杂数据结构时非常灵活,比如查找对象数组中某个特定属性值的对象。

const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];// 查找 id 为 2 的用户的索引const bobIndex = users.findIndex(user => user.id === 2);console.log(bobIndex); // 输出: 1// 查找 name 包含 'ice' 的用户的索引const aliceIndex = users.findIndex(user => user.name.includes('ice'));console.log(aliceIndex); // 输出: 0// 查找一个不存在的条件const charlieIndex = users.findIndex(user => user.name === 'Charlie');console.log(charlieIndex); // 输出: -1

所以,当你只需要找到一个精确匹配的原始值时,用

indexOf

既简洁又高效。但如果你的查找条件更复杂,或者你正在处理对象数组,那么

findIndex

几乎总是更好的选择。

如何用 indexOf 查找所有匹配元素的索引?

indexOf()

的一个“缺点”是它只会返回第一个找到的元素的索引。如果你想找出某个元素在数组中所有出现的位置,光靠

indexOf()

是不够的,你需要结合循环来反复调用它,并巧妙地利用它的

fromIndex

参数。

思路是这样的:先找到第一个,然后从第一个的下一个位置开始继续找,直到找不到为止。

下面是一个实现这个逻辑的例子:

function findAllIndices(arr, searchElement) {    const indices = [];    let currentIndex = arr.indexOf(searchElement); // 首次查找    while (currentIndex !== -1) {        indices.push(currentIndex); // 找到了,记录下来        // 从当前找到的索引的下一个位置开始继续查找        currentIndex = arr.indexOf(searchElement, currentIndex + 1);    }    return indices;}const numbers = [1, 2, 3, 2, 4, 2, 5];const allTwoIndices = findAllIndices(numbers, 2);console.log(allTwoIndices); // 输出: [1, 3, 5]const allOneIndices = findAllIndices(numbers, 1);console.log(allOneIndices); // 输出: [0]const allSixIndices = findAllIndices(numbers, 6);console.log(allSixIndices); // 输出: []

这个

while

循环的模式非常经典且实用,它能有效地遍历数组中所有符合条件的元素。每次找到一个,我们就把它的索引存起来,然后把下一次

indexOf

的起始位置设置到当前找到的索引的后一位,这样就能避免重复找到同一个元素,并确保能找到所有后续的匹配项。

indexOf 在处理特殊值(如 NaN 或 undefined)时有什么需要注意的?

在 JavaScript 中,一些特殊的值在比较行为上会有一些“怪异”的地方,这也会影响到

indexOf()

的表现。了解这些能帮助你避免一些潜在的坑。

NaN

(Not-a-Number): 这是最需要注意的一个。

indexOf()

无法找到

NaN

。这是因为

NaN

在 JavaScript 中有一个独特的性质:它不等于任何值,包括它自己 (

NaN === NaN

的结果是

false

)。因此,

indexOf

依赖的严格相等比较对

NaN

是无效的。

const weirdNumbers = [1, 2, NaN, 3];console.log(weirdNumbers.indexOf(NaN)); // 输出: -1

如果你需要查找数组中是否存在

NaN

,或者找到

NaN

的索引,你不能用

indexOf()

。这时,

findIndex()

就能派上用场,你可以结合

isNaN()

函数来判断:

console.log(weirdNumbers.findIndex(item => isNaN(item))); // 输出: 2

或者,如果你只是想知道数组中是否包含

NaN

Array.prototype.includes()

是一个更好的选择,因为它能正确处理

NaN

console.log(weirdNumbers.includes(NaN)); // 输出: true

undefined

:

indexOf()

可以正常找到

undefined

const mixedValues = [1, undefined, 3, null];console.log(mixedValues.indexOf(undefined)); // 输出: 1

null

:

indexOf()

同样可以正常找到

null

const mixedValues = [1, undefined, 3, null];console.log(mixedValues.indexOf(null)); // 输出: 3

总之,

indexOf()

是一个非常实用的数组方法,尤其适用于查找原始类型的值。但在处理对象、复杂查找逻辑或

NaN

这样的特殊值时,了解它的局限性并知道何时转向

findIndex()

或其他方法,是写出健壮且高效 JavaScript 代码的关键。

以上就是js 如何用indexOf查找数组中元素的索引的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1516848.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
事件循环中的“低优先级”任务是什么?
上一篇 2025年12月20日 10:20:45
JS如何实现天气查询
下一篇 2025年12月20日 10:20:54

相关推荐

发表回复

登录后才能评论
关注微信