javascript if number greater than number

后端 未结 4 1832
梦毁少年i
梦毁少年i 2020-11-29 04:38

I have this javascript function to validate if a number is greater than another number

function validateForm() {
    var x = document.forms[\"frmOrder\"][\"t         


        
4条回答
  •  误落风尘
    2020-11-29 05:24

    You're comparing strings. JavaScript compares the ASCII code for each character of the string.

    To see why you get false, look at the charCodes:

    "1300".charCodeAt(0);
    49
    "999".charCodeAt(0);
    57
    

    The comparison is false because, when comparing the strings, the character codes for 1 is not greater than that of 9.

    The fix is to treat the strings as numbers. You can use a number of methods:

    parseInt(string, radix)
    parseInt("1300", 10);
    > 1300 - notice the lack of quotes
    
    
    +"1300"
    > 1300
    
    
    Number("1300")
    > 1300
    

提交回复
热议问题