JavaScript不比较最小大于最大数值 [英] JavaScript not comparing minimum greater than maximum number values
问题描述
为什么JavaScript中的数字值的大于比较无效。下面的示例即使在迷你数小于maxi时仍保持返回true。
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和maxi是表单输入值。此示例使用jQuery获取值,但可以轻松地剥离。
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 );
}
将mini> maxi替换为Math.max(mini,maxi) == 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 );
}
推荐答案
from string
Use this line to get Int from String
if( parseInt(mini.valueOf(),10) < parseInt(maxi.valueOf(),10) ) { //also used: mini > maxi
sinve你可以从字符串dom得到值。你应该把它们解析成Int,然后比较。
此外,最好将10作为第二个参数,以确保该数字将被解析为十进制。
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.
这篇关于JavaScript不比较最小大于最大数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!