(Built-in) way in JavaScript to check if a string is a valid number

前端 未结 30 3352
-上瘾入骨i
-上瘾入骨i 2020-11-22 01:54

I\'m hoping there\'s something in the same conceptual space as the old VB6 IsNumeric() function?

30条回答
  •  旧巷少年郎
    2020-11-22 02:22

    function isNumberCandidate(s) {
      const str = (''+ s).trim();
      if (str.length === 0) return false;
      return !isNaN(+str);
    }
    
    console.log(isNumberCandidate('1'));       // true
    console.log(isNumberCandidate('a'));       // false
    console.log(isNumberCandidate('000'));     // true
    console.log(isNumberCandidate('1a'));      // false 
    console.log(isNumberCandidate('1e'));      // false
    console.log(isNumberCandidate('1e-1'));    // true
    console.log(isNumberCandidate('123.3'));   // true
    console.log(isNumberCandidate(''));        // false
    console.log(isNumberCandidate(' '));       // false
    console.log(isNumberCandidate(1));         // true
    console.log(isNumberCandidate(0));         // true
    console.log(isNumberCandidate(NaN));       // false
    console.log(isNumberCandidate(undefined)); // false
    console.log(isNumberCandidate(null));      // false
    console.log(isNumberCandidate(-1));        // true
    console.log(isNumberCandidate('-1'));      // true
    console.log(isNumberCandidate('-1.2'));    // true
    console.log(isNumberCandidate(0.0000001)); // true
    console.log(isNumberCandidate('0.0000001')); // true
    console.log(isNumberCandidate(Infinity));    // true
    console.log(isNumberCandidate(-Infinity));    // true
    
    console.log(isNumberCandidate('Infinity'));  // true
    
    if (isNumberCandidate(s)) {
      // use +s as a number
      +s ...
    }
    

提交回复
热议问题