javascript: string conversion value

isNaN(i.value)//Used to determine whether i.value is not a number//NaN not a number is not a number


        i represents a text input box
      1. i.value gets a string, and when the string is -*/ (subtraction, multiplication and division), it will be automatically converted into a numerical value for operation
      2. If it is +, the string concatenation "5" is performed *"5"-> 5*5, "5"+"5" is spliced ​​into "55"
        //d.innerText = "result:"+i.value+i.value;
      3. Convert the string into a numeric value Ways:
        //3.1. parseInt to integer or parseFloat to decimal
        //d.innerText = "Result:"+(parseInt(i.value)+parseInt(i.value)); //3.2
        . Let string *1 Force the string to be converted to the value "5"*1-> 5*1 = 5
        d.innerText = "result:"+(i.value*1+i.value*1);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" id="i1">
<input type="button" value="平方" onclick="fn()">
<div>结果:0</div>
<script>
    function fn() {
        //得到文本框和div
        let d = document.querySelector("div");
        let i = document.querySelector("#i1");
        //判断用户输入的内容是否是数值
        if (isNaN(i.value)){//满足条件说明是NaN 不是数
            d.innerText="输入格式错误!";
            return;
        }
        //把文本框的值 相乘 后的结果给到div
        //d.innerText = "结果:"+i.value*i.value;
        //i.value得到的是字符串,字符串进行-*/时会自动转成数值进行运算
        //如果是+ 则进行的是字符串拼接  "5"*"5"-> 5*5, "5"+"5"拼接成"55"
        //d.innerText = "结果:"+i.value+i.value;
        //将字符串转成数值两种方式:
        //1. parseInt转整数或parseFloat转小数
        //d.innerText = "结果:"+(parseInt(i.value)+parseInt(i.value));
        //2. 让字符串*1  强制字符串转成数值 "5"*1-> 5*1 = 5
        d.innerText = "结果:"+(i.value*1+i.value*1);


    }
</script>
</body>
</html>

Guess you like

Origin blog.csdn.net/gulanga5/article/details/124429307