在JavaScript数组中查找NaN的索引 [英] Find index of NaN in a javascript array

查看:158
本文介绍了在JavaScript数组中查找NaN的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[1, 2, 3].indexOf(3) => 2

[1, 2, NaN].indexOf(NaN) => -1

[1, NaN, 3].indexOf(NaN) => -1

推荐答案

您可以使用

You can use Array.prototype.findIndex method to find out the index of NaN in an array

let index = [1,3,4,'hello',NaN,3].findIndex(Number.isNaN)
console.log(index)

您可以使用 Array.prototype.includes 检查数组中是否存在NaN.它不会给你索引!它将返回一个布尔值.如果存在NaN,则返回true,否则返回false

You can use Array.prototype.includes to check if NaN is present in an array or not. It won't give you the index though !! It will return a boolean value. If NaN is present true will be returned, otherwise false will be returned

let isNaNPresent = [1,2,NaN,'ball'].includes(NaN)
console.log(isNaNPresent)

请勿使用Array.prototype.indexOf

Don't use Array.prototype.indexOf

您不能使用 Array.Prototype. indexOf 查找 NaN 在数组中.因为indexOf使用 strict-quality-运算符内部,而 NaN === NaN 的值为 false .因此indexOf将无法检测数组内部的NaN

You can not use Array.Prototype.indexOf to find index of NaN inside an array.Because indexOf uses strict-equality-operator internally and NaN === NaN evaluates to false.So indexOf won't be able to detect NaN inside an array

[1,NaN,2].indexOf(NaN) // -1

使用Number.isNaN代替isNaN:

Use Number.isNaN instead of isNaN :

在这里,我选择 Number.isNaN isNaN 上进行操作.因为isNaNstring literal视为NaN,另一方面Number.isNaN仅将NaN文字视为NaN

Here i choose Number.isNaN over isNaN. Because isNaN treats string literal as NaN.On the other hand Number.isNaN treats only NaN literal as NaN

isNaN('hello world') // true
Number.isNaN('hello world') // false

或者,编写您自己的逻辑:

Or, Write your own logic :

您可以编写自己的逻辑来查找NaN.您已经知道,NaN是javascript中唯一的值not equal to itself.这就是我建议不要使用Array.prototype.indexOf的原因.

You can write your own logic to find NaN.As you already know that, NaN is the only value in javascript which is not equal to itself. That's the reason i suggested not to use Array.prototype.indexOf.

NaN === NaN // false

我们可以使用这个想法来编写我们自己的isNaN函数.

We can use this idea to write our own isNaN function.

[1,2,'str',NaN,5].findIndex(e=>e!=e) // 3

这篇关于在JavaScript数组中查找NaN的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆