0098 to digital conversion of data types: parseInt, parseFloat, Number (), implicit conversion

8.4.2. Converted to a digital type (Key)

  • Note that the case of parseInt and parseFloat word, which is the key [2 parseInt: rounding, taken at the beginning of the digital number at the beginning of the object; not rounded, truncated directly; begins with a number of non-target parameters, the result is NaN. ]
  • Implicit conversion is when we conduct arithmetic, JS automatically convert data types

        // var age = prompt('请输入您的年龄');
        // 1. parseInt(变量)  可以把 字符型的转换为数字型 得到是整数
        // console.log(parseInt(age));
        console.log(parseInt('3.14')); // 3 取整
        console.log(parseInt('3.94')); // 3 取整
        console.log(parseInt('120px')); // 120 会去到这个px单位
        console.log(parseInt('rem120px')); // NaN
        // 2. parseFloat(变量) 可以把 字符型的转换为数字型 得到是小数 浮点数
        console.log(parseFloat('3.14')); // 3.14
        console.log(parseFloat('120px')); // 120 会去掉这个px单位
        console.log(parseFloat('rem120px')); // NaN,发现开头不是数字
        // 3. 利用 Number(变量) 
        var str = '123';
        console.log(Number(str));
        console.log(Number('12'));
        // 4. 利用了算数运算 -  *  /  隐式转换
        console.log('12' - 0); // 12
        console.log('123' - '120');
        console.log('123' * 1);
        demo:计算年龄
        // 弹出一个输入框(prompt),让用户输入出生年份 (用户输入)
        // 把用户输入的值用变量保存起来,然后用今年的年份减去变量值,结果就是现在的年龄  (程序内部处理)
        // 弹出警示框(alert) , 把计算的结果输出 (输出结果)
        var year = prompt('请您输入您的出生年份');
        var age = 2018 - year; // year 取过来的是字符串型  但是这里用的减法 有隐式转换
        alert('您今年已经' + age + '岁了');
        demo:简单加法计算器
        // 先弹出第一个输入框,提示用户输入第一个值  保存起来
        // 再弹出第二个框,提示用户输入第二个值  保存起来
        // 把这两个值相加,并将结果赋给新的变量(注意数据类型转换)  
        // 弹出警示框(alert) , 把计算的结果输出 (输出结果)
        var num1 = prompt('请您输入第一个值:');
        var num2 = prompt('请您输入第二个值:');
        var result = parseFloat(num1) + parseFloat(num2);
        alert('您的结果是:' + result);

Guess you like

Origin www.cnblogs.com/jianjie/p/12128568.html