javascripttypescriptisnan

IsNaN shows other results


let args: string[] = process.argv.slice(2);
console.log(`All arguments: ${args}`);

let numbers: number[] = saveNumbers();
console.log(`All Numbers: ${numbers}`);

console.log(`1st argument < 10: ${firstNumberFullfill(numbers,x => x < 10)}`);

console.log(`1st argument > 10: ${firstNumberFullfill(numbers,x => x > 1000)}`);

console.log(`1st not numerical argument: ${firstNumberFullfill(args,x => isNaN(x))}`);

function saveNumbers():number[]{
    let nums: number[] = [];

    for(let a of args){
        let num = parseInt(a);
        if(isNaN(num) == false){
            console.log(a)
            nums.push(parseInt(a));
        }
    }
    return nums;
}

function firstNumberFullfill(array: Array<any>,checkFunc: (num: number) => boolean):number|string{
    for(let a of array){
        if(checkFunc(a)){
            return a;
        }
    }
    return "no number found";
}
        

console output

My IsNaN says "12ab" is a number but at the first Non-Number argument its the first non-number, i used the isNaN function twice so idk why it doesnt work


Solution

  • You're not comparing the same values here: the first check (saveNumbers) tests isNaN(parseInt("12ab")) while the second tests isNaN("12ab").

    saveNumbers will parse "12ab" and return 12, which is a number and not NaN, while isNaN("12ab") will show that the String you pass is indeed NaN.