开发者

Why does this return NaN?

model.qty = (parseInt(开发者_开发问答$('#amendOrderQty').val()) == NaN) ? 
  0 : 
  parseInt($('#amendOrderQty').val());

// model.qty === NaN when #amendOrderQty is left blank

I am trying to set a value of 0 when the field is left blank. Why does this not work?


You cannot use the comparison operator with NaN, it will always return false.

Use isNaN() instead

var qty = parseInt($('#amendOrderQty').val());
model.qty = isNaN(qty) ? 0 : qty;


Use "isFinite" instead.

var x = parseInt($('#amendOrderQty').val();
model.qty = isFinite(x) ? x : 0;


You cannot directly compare something to NaN because

NaN === NaN

always returns false.


In light of this, you should replace

parseInt($('#amendOrderQty').val()) == NaN

with

isNan(parseInt($('#amendOrderQty').val()))


Your code, refactored and fixed, should look something like this:

var orderQtyVal = parseInt($('#amendOrderQty').val());
model.qty = isNaN(orderQtyVal) ? 0 : orderQtyVal;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜