JS 数据类型转换 (很小的知识点但是是基础)

有些时候,需要将数据转换为其他类型进行操作,转换方式:强制转换、隐式转换

强制转换

通过方法,将数据必须转换为某种数据类型

 强制转换为number

  • Number(要转换的数据) : 强制转换为number类型,不能转换的结果为NaN

  • parseInt(要转换的数据) : 从左往右开始转换,遇到不能转换的或者是末尾就停止,如果一开始就不能转换结果为NaN,取整

  • parseFloat(要转换的数据):从左往右开始转换,遇到不能转换的或者是末尾就停止,如果一开始就不能转换结果为NaN,保留小数

    //1.Number(要转换的数据类型):强制转为number类型,会将转换后的结果返回
    //字符串转Number----  纯数字,空字符
    var s1 = "10";
    var s2 = "10a";
    var s3 = "";
    console.log(Number(s1));  //"10" ---- 10
    console.log(Number(s2));  //NaN
    console.log(Number(s3));  //0
    ​
    //boolean转number
    var b1 = true;
    var b2 = false;
    console.log(Number(b1),Number(b2)); //1  0
    ​
    //null转number
    var nu = null;
    console.log(Number(nu)); //0
    ​
    //undefined转number
    var u = undefined;
    console.log(Number(u)); //NaN
    ​
    //2.parseInt(要转换的数据):从左往右开始转换,遇到不能转换的或者是末尾就停止,如果一开始就不能转换结果为NaN,取整
    //3.parseFloat(要转换的数据):从左往右开始转换,遇到不能转换的或者是末尾就停止,如果一开始就不能转换结果为NaN
    var price = "9.9元";
    console.log(parseInt(price)); //9  舍弃小数部分
    console.log(parseFloat(price)); //9.9  保留小数

强转转换为string

  • String(要转换的内容) : 强制转为string,就是在数据的外层加了引号

    //1.String(要转换的内容) : 强制转为string,就是在数据的外层加了引号
    var n = 10;
    console.log(String(n),n); //"10"
    console.log(String(true));  //"true"
    console.log(String(false)); //"false"
    console.log(String(null));  //"null"
    console.log(String(undefined));//"undefined"
    console.log(String(NaN));//"NaN"

  • XX.toString()

    //2  XX.toString()
    var n = 10;
    console.log(n.toString());
    var b = true;
    console.log(b.toString()); 
    //undefined身上没有任何方法,只要是undefiend. 都报错
    var u = undefined;
    //console.log(u.toString()); //Cannot read property 'toString' of undefined 
    ​
    // null身上没有任何方法,只要是 null. 都报错
    var nu = null;
    console.log(nu.toString()); //Cannot read property 'toString' of null
  • String和toString的区别?

    String是公共方法,toString是对象私有的方法,undefined和没有没有

 隐式转换

在运算过程中数据自动进行类型转换

  • isNaN

    isNaN : is not a number ,判断数据是否是一个数字,是数字-false,不是数字-true

    //1.isNaN : is not a number ,判断数据是否是一个数字,是数字-false,不是数字-true
    console.log(isNaN(10));//false
    console.log(isNaN("a"));//true
    ​
    //isNaN在判断之前,会自动调用Number()先将数组转换为number,在判断
    console.log(isNaN("10")); //false Number("10") --- > 10    isNaN(10)
    console.log(isNaN(null)); //false   null-->0
    console.log(isNaN(true)); //false   true--1

  • toFixed()

    xx.toFixed(n) : 保留几位小数,四舍五入

    //2.xx.toFixed(n) : 保留几位小数,四舍五入
    var a = 0.1;
    var b = 0.2;
    console.log((a + b).toFixed(1)); //0.3
    var n = 3.4567;
    console.log(n.toFixed(2)); //3.46

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值