Muflix Muflix - 2 months ago 15
Javascript Question

How to check existence of NaN keyword in an array?

I have following array

var arr = [7, 1, "abc", undefined, NaN];


but how can i check if the value in arr is a NaN ?

for (i=0; i < arr.length; i++){

// check if array value is false or NaN
if (arr[i] === false || arr[i] === NaN) {
// do something
}

}


any idea ? I tried
isNaN(arr[i])
function but it is also not working.

Answer

In ECMAScript 6 you can use the Number.isNaN function:

var arr = [7, 1, "abc", undefined, NaN];

for (i=0; i < arr.length; i++){

    // check if array value is false or NaN
    if (arr[i] === false || Number.isNaN(arr[i])) {
        console.log("NaN found at place " + i);
    }

  }

If you need to work in ECMAScript 5 then the problem with the isNaN function is that it is checking to see if the value is able to be coerced into a number. Instead you could use the odd property of the NaN value - it isn't equal to itself:

var arr = [7, 1, "abc", undefined, NaN];

for (i=0; i < arr.length; i++){

    // check if array value is false or NaN
    if (arr[i] === false || arr[i] != arr[i]) {
        console.log("NaN found at place " + i);
    }

  }
Comments