JavaScript not comparing minimum greater than maximum number values

半腔热情 提交于 2019-12-11 17:55:58

问题


Why is "greater than" comparisons for number values in JavaScript not working. The example below keeps returning true even when the mini number is less than the maxi.

mini and maxi are form input values. This example is using jQuery to get the values, but could easily be stripped.

var mini = $('form#filterPrice input.min').val(); //eg. 500
var maxi = $('form#filterPrice input.max').val(); //eg. 1500

if( mini.valueOf() > maxi.valueOf() ) { //also used: mini > maxi
    alert('test'); //alerts "test" even when mini is less than maxi
$('form#filterPrice input.min').val( maxi ); //should switch values if mini > maxi
$('form#filterPrice input.max').val( mini );
}

Replacing "mini > maxi" with "Math.max(mini, maxi) == mini" works fine. So, the following does work:

var mini = $('form#filterPrice input.min').val(); //eg. 500
var maxi = $('form#filterPrice input.max').val(); //eg. 1500

if( Math.max(mini, maxi) == mini ) {
    alert('test'); 
$('form#filterPrice input.min').val( maxi );
$('form#filterPrice input.max').val( mini );
}

回答1:


Use this line to get Int from String

if( parseInt(mini.valueOf(),10) < parseInt(maxi.valueOf(),10) ) { //also used: mini > maxi

sinve you get values to compare from dom like a string. Fist you should parse them into Int and only then compare. Also it is better to put 10 as a second param to be sure the number will be parsed as decimal.




回答2:


in first example you are comparing strings and "1500" < "500". In second example Math.max converts the values to numbers.



来源:https://stackoverflow.com/questions/1266723/javascript-not-comparing-minimum-greater-than-maximum-number-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!