Return 如果输入值为 NaN 则为零
Return Zero if input value is NaN
有没有最好的预防方法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} />
现在在我的渲染中我有 400 - this.state.amount
。问题是,当我清除输入字段时,金额状态为 null
。如何防止这种情况?是否有可能当我清除该字段时我得到零?假设我输入 3
然后清除字段,弹出 NaN
。
谢谢
NaN
is never equals to anything including NaN
itself hence rely on Number.isNaN(value)
method.
_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;
}
isNaN
功能的必要性
Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (==
and ===
) to determine whether a value is NaN
or not, because both NaN == NaN
and NaN === NaN
evaluate to false. Hence, the necessity of an isNaN
function.[Ref]
我找到的最短路线是
var number = (yourVariable || 0)
因为 NaN
是一个假值,只要 yourVariable
是 NaN,这将 return 0。
一种检查数字是否为 NaN 的方法是使用 isNaN
函数。
isNaN(yourVariable); // Returns true is yourVariable is NaN
旁注:
以上方法也可以用于多种问题。例如:从数组中获取值(可能不存在)并从二维数组中获取值。
从数组获取值:
yourArray[i] || 0
其中i
是您要访问的id
从二维数组获取值:
(yourArray[i] || [])[j] || 0
其中i
和j
是元素在数组中的位置
有没有最好的预防方法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} />
现在在我的渲染中我有 400 - this.state.amount
。问题是,当我清除输入字段时,金额状态为 null
。如何防止这种情况?是否有可能当我清除该字段时我得到零?假设我输入 3
然后清除字段,弹出 NaN
。
谢谢
NaN
is never equals to anything includingNaN
itself hence rely onNumber.isNaN(value)
method.
_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;
}
isNaN
功能的必要性
Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (
==
and===
) to determine whether a value isNaN
or not, because bothNaN == NaN
andNaN === NaN
evaluate to false. Hence, the necessity of anisNaN
function.[Ref]
我找到的最短路线是
var number = (yourVariable || 0)
因为 NaN
是一个假值,只要 yourVariable
是 NaN,这将 return 0。
一种检查数字是否为 NaN 的方法是使用 isNaN
函数。
isNaN(yourVariable); // Returns true is yourVariable is NaN
旁注:
以上方法也可以用于多种问题。例如:从数组中获取值(可能不存在)并从二维数组中获取值。
从数组获取值:
yourArray[i] || 0
其中i
是您要访问的id
从二维数组获取值:
(yourArray[i] || [])[j] || 0
其中i
和j
是元素在数组中的位置