如果输入值为NaN,则返回零

Syl*_*lar -3 javascript math nan reactjs

有最好的预防方法NaN吗?我有数字输入字段,每当我清除字段时,我得到NaN.

_amount: function(e) {
  var value = parseInt(e.target.value);
  var newValue = (value === NaN ? 0 : value); // Thought this could work
},

<input type="number" value={this.state.amount} onChange={this_amount} />
Run Code Online (Sandbox Code Playgroud)

现在在我的渲染中我有400 - this.state.amount.事情是,当我清除输入字段时,金额状态是null.怎么预防这个?有可能当我清除该字段时我得到零吗?假设我输入3然后清除该字段,NaN弹出.

谢谢

Ray*_*yon 9

NaN永远不等于包括NaN其本身在内的任何东西因此依赖于Number.isNaN(value)方法.

_amount: function(e) {
  var value = parseInt(e.target.value);
  var newValue = (isNaN(value) ? 0 : value);

  //OR sorthand as `NaN` is falsey
  var value = parseInt(e.target.value) || 0;
}
Run Code Online (Sandbox Code Playgroud)

isNaN功能的必要性

与JavaScript中的所有其他可能值不同,不可能依赖等于运算符(=====)来确定值是否为值NaN,因为两者都是NaN == NaN并且NaN === NaN求值为false.因此,isNaN功能的必要性.[ 参考 ]