JS数据类型转换

JS数据类型转换

  • 把字符串转化为数字,转化不了的就是NaN
    • Number
1
2
3
4
5
6
7
8
9
10
console.log(Number("100")) //100 
console.log(Number("")) //0
console.log(Number(false)) //0
console.log(Number(" ")) //0
console.log(Number([123])) //123
console.log(Number(null)) //0
console.log(Number(undefined)) //NaN
console.log(Number({})) //NaN
console.log(Number(function(){})) //NaN
console.log(Number('100px')) //NaN
  • parseInt和parseFloat 一个只能转出整数部分,一个能转出小数部分
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    var a = '100px';
    alert(parseInt(a)); //100

    var b = '100px123456789';
    alert(parseInt(b)); //100

    var d = '-100px';
    alert(parseInt(d)); //-100 parseInt还是认加减号的

    var e = ' 100px';
    alert(parseInt(e)); //100 parseInt也是认空格的

    var f = '000000100px';
    alert(parseInt(f)); //100

    var g = '12.34元';
    alert(parseInt(g)); //12 parseInt只能转出整数
    var c = true;
    alert(parseInt(c)); //NaN

    //parseInt也不能用于转函数等
  • parseInt和parseFloat配合使用,来判断是整数还是小数

1
2
3
4
5
6
var num = '200.345';
if(parseInt(num) == parseFloat(num)) {
alert(num + '是整数');
} else {
alert(num + '是小数');
}
  • 隐形类型转化
    • -*/%可以将字符串转化为数字
    • +号可以将数字转换为字符串
    • ++ –可以将字符串转化为数字
    • <> 可以将字符串转化为数字
    • ! 可以将数据类型转化为布尔型
    • ==