Why isNaN('') or isNaN(“”) is false (one quote or double quotes are considered a valid number)?

后端 未结 3 1554
傲寒
傲寒 2021-01-27 23:49

I need a built in function that checks if a variable contains a valid number in Javascript , following this link I\'ve tried to use is isNaN , however when I use on

3条回答
  •  情歌与酒
    2021-01-27 23:57

    Converting an empty string to Number will evaluate to 0. Same goes for booleans (+false = 0, +true = 1), and null. If that's unwanted, you can create your own function to determine if some (string) value can be converted to Number. See also (the examples @) MDN.

    const canConvert2Number = value =>
          !value ||
          value === false ||
          value === true ||
          value === null || 
          String(value).trim().length < 1
          ? false
          : !isNaN(+value);
    
    console.log(canConvert2Number(null));    //false
    console.log(canConvert2Number(""));      //false
    console.log(canConvert2Number());        //false
    console.log(canConvert2Number(false));   //false
    console.log(canConvert2Number(true));    //false
    console.log(canConvert2Number("[]"));    //false
    console.log(canConvert2Number("{}"));    //false
    console.log(canConvert2Number("20.4"));  //true
    console.log(canConvert2Number("10E4"));  //true
    .as-console-wrapper { top: 0; max-height: 100% !important; }

提交回复
热议问题