Input value is a string instead of a number

前端 未结 4 1716
日久生厌
日久生厌 2020-11-29 13:08

When i add a number to the input it doesn\'t change the value that stays at 5 and when i go in the console and type uw.value i get \"6\" back instead of 6 which i typed in

4条回答
  •  难免孤独
    2020-11-29 13:37

    Since input HTMLElement.value returns a "String"....

    jsbin demo

    Convert your "String" number to Number by using

    parseInt(value, 10);  // for (whole) integer numbers
    parseFloat(value);    // for (point) floated numbers
    Number(value);        // to Number Object
    

    or by simply adding a unary + before the value:

    +value; // instead of parseInt()
    

    To be totally sure your value is a number you can also do:

    if(!isNaN(parseFloat(el.value)) && isFinite(el.value)){
       /*true if element's value is a number (or a number in string) */
    }
    

    For example:

    var uw = document.getElementById("wakken");
    var ui = document.getElementById("ijsberen");
    var up = document.getElementById("penguins");
    
    function check() {
      // Log Strings
      console.log(uw.value);                  // "5"
      console.log(ui.value);                  // "5"
      console.log(up.value);                  // "0"
      // Log Numbers
      console.log(Number(uw.value));          // 5
      console.log(+uw.value);                 // 5
      console.log(parseInt(ui.value, 10));    // 5
      console.log(parseFloat(up.value));      // 0
    }
    

    Don't forget to: read the Docs
    parseInt()
    parseFloat()
    Number()
    Arithmetic operators

提交回复
热议问题