Find index of NaN in a javascript array

前端 未结 3 2139
清歌不尽
清歌不尽 2021-01-04 07:16
[1, 2, 3].indexOf(3) => 2

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

[1, NaN, 3].indexOf(NaN) => -1
3条回答
  •  别那么骄傲
    2021-01-04 07:51

    You have to look at each item to return an array of the indexes that are NaN values-

    function findNaNs(arr){
        return arr.map(function(itm, i){
            if(isNaN(itm)) return i;
            return false;
        }).filter(function(itm){
            return itm;
        });
    }
    

    findNaNs([1, NaN, 3, 4, 'cat'/3])

    //or to find the first one-

    function firstNaN(arr){
        var i= 0, L= arr.length;
        while(i

提交回复
热议问题