如何在 JavaScript 中轻松检查变量是否为数字?

How do you easily check whether a Variable is number or not in JavaScript?

我不是 JavaScript 开发人员,但我只想知道检查变量是否包含数字的正确方法。经过几次分析后,我找到了以下解决方案。方法正确吗?

function calculation(n1,n2 , ...numbers) {

  let validateNumber = (num) => {
    if(num !== num)
      return 0;
      else
    return typeof num === 'number' ? num : 0;
  }

  let sum =0;
  for(n of numbers){
    sum += validateNumber(n);
  }
  console.log(sum);
} 

calculation(5,6,7,'gg','',null, NaN, undefined,  null,8,9,5.4,10);

请检查 'validateNumber' 箭头函数。

是的,它也是一个班轮

export const isNum = n => Number(n) === Number(n);

首先解析为你得到的 Eva 参数与自身进行比较的编号。 JavaScript 附带的其中一个 what the hell'sNaN !== NaN 所以如果你在强制它成为一个数字后得到的值变成一个 Nan 它将与它自己不同

是的,JavaScript 中有内置函数来检查某个值是否为数字,即 isNaN()

如果你想获得数组中所有数字的总和,那么你可以尝试使用 reduce(),如下所示:

var data = [5,6,7,'gg','',null, NaN, undefined,  null,8,9,5.4,10];
var sum = data.reduce((a,c) =>{
  if(!isNaN(c)){
    a = a + Number(c); //convert the '' and null to 0 with Number()
  }
  
  return a;
},0);
console.log(sum)

第一个版本=>
-- 只需使用 isNaN() : sum+(isNaN(val)?0:Number(val)

第二个版本(在评论中询问)=>
-- 只是使用严格的比较。仅获取数字类型值。

const calculation =(...numbers)=>  // (n1,n2 , ...numbers)=>
  numbers.reduce((sum,val)=>
    sum + (Number(val)===val ? val : 0)  // sum+(isNaN(val)?0:Number(val))
    , 0);

console.log( calculation(5,6,7,'gg','',null, NaN, undefined,  null,8,9,5.4,'10') )

For more clarity, here it is a table showing the execution of the test according to the different possible types

const
  testFunction = val => Number(val)===val
, values =
  [ { v: 123,       display: `123`,       expected: true  }
  , { v: '123',     display: `"123"`,     expected: false }
  , { v: NaN,       display: `NaN`,       expected: false }
  , { v: undefined, display: `undefined`, expected: false }
  , { v: null,      display: `null`,      expected: false }
  ]
, tBody = document.querySelector('table > tbody')
  ;
let score = 0
  ;
for (let {v, display, expected} of values)
  {
  let
    TR  = tBody.insertRow()
  , res = testFunction(v)
    ;
  score += expected===res ? 1 : 0
  TR.insertCell().textContent = display
  TR.insertCell().textContent = expected
  TR.insertCell().textContent = res
  TR.insertCell().className   = expected===res ? 'ok' : 'bad'
  }
document.querySelector('table >tfoot td:nth-of-type(2)')
  .textContent = `${score} / ${values.length}`
table { font-family: Arial, Helvetica, sans-serif;border-collapse: collapse;margin: 0 1em; }
td    { padding: .2em .8em;border: 1px solid darkblue; } 
thead,tfoot {  background-color: #84a4ce;text-transform: capitalize; }
caption     { padding: .3em;caption-side: bottom;font-size: .8em; }
.ok:before,.bad:before { font-weight: bold;font-size: 1.2em; }
.ok:before  { color: green;content: '13'; }
.bad:before { color: red;  content: '18'; }
<table>
  <caption>( Number(val)===val ) ?</caption>
  <thead>
    <tr> <td>val</td><td>expected</td><td colspan="2">result</td> </tr>
  </thead>
  <tbody></tbody>
  <tfoot>
    <tr> <td colspan="3">score</td><td>0/0</td> </tr>
  </tfoot>
</table>

您可以filter out the elements that aren't numbers by checking to see if they're not null and also a number, and then using reduce总结元素。

function calculation(n1, n2, ...elements) {
  
  return elements

    // `filter` out the elements that are numbers
    .filter(el => el && Number(el))

    // Add them all up
    .reduce((acc, c) => acc + c, 0);
}

console.log(calculation(5,6,7,'gg','',null, NaN, undefined,  null,8,9,5.4,10));