js 强制类型转换 和 隐式类型转换 和 Unicode编码

强制类型转换

一、其他数据类型 强制转换为 String
方法1: toString()方法

let a = 123
a =a.toString()
console.log(a,typeof(a),'111'); //123 string 111

在这里插入图片描述

let b = null
b = b.toString()
console.log(b,typeof(b),'222'); //TypeError: Cannot read properties of null (reading 'toString')

let c = undefined
c = c.toString()
console.log(c,typeof(c),'222'); //TypeError: Cannot read properties of undefined (reading 'toString')

*方法2:String()函数 *

let a = 123
 a = String(a)
 console.log(a,typeof(a),'111');  // 123 string 111

String()函数还能将 null 和 undefined 转为 string类型;

let b = null
b = String(b)
console.log(b,typeof(b),'222');  // null string 222

let c = undefined
c = String(c)
console.log(c,typeof(c),'333'); // undefined string 333

二、其他数据类型 强制转换为 Number
方法1:Number()函数
在这里插入图片描述
在这里插入图片描述

let name = ''
name = Number(name)
console.log(name,typeof(name)); //0 'number'

let sex = '    '
sex = Number(sex)
console.log(sex,typeof(sex)); //0 'number'
        
let a = "123"
a = Number(a)
console.log(a,typeof(a)); //123 'number'


let b = "123a"
b = Number(b)
console.log(b,typeof(b)) //NaN 'number'

let c = null
c = Number(c)
console.log(c,typeof(c)); //0 'number'

let d = undefined
d = Number(d)
console.log(d,typeof(d)); //NaN 'number'

方法2:parseInt() 、parseFloat()
在这里插入图片描述

let a = "123dfsl"
a = parseInt(a)
console.log(a,typeof(a)); //123 'number'

let b = "b123"
b = parseInt(b)
console.log(b,typeof(b)); //NaN 'number'

let c = "123.365ab"
c = parseInt(c)
console.log(c,typeof(c)); //123 'number'

let d = "123.365ab"
d = parseFloat(d)
console.log(d,typeof(d)); //123.365 'number'

在这里插入图片描述

 let a = true
 a= parseInt(a)
 console.log(a,typeof(a)); //NaN 'number'

三、其他数据类型 强制转换为 Boolean
在这里插入图片描述

隐式类型转换

逻辑运算符 !、&&、||
!(非)
在这里插入图片描述
非运算会先将 a 转为boolean类型,“hello” 的boolean类型为 true, !a 为 false,!!a 为 true;所以 !!a 是将 a 转为它的boolean值;

&& (与)
在这里插入图片描述
在这里插入图片描述
&&(与)是找false,如果第一个值为false,就不会执行第二个值了

||(或)
在这里插入图片描述
在这里插入图片描述

||(或)是找true,如果第一个值为true,就不会执行第二个值了。

在这里插入图片描述

let a = 3 && 0
console.log(a); // 0

let a = NaN && 2
console.log(a); //NaN

let b = 'hellow' || ''
console.log(b); // hellow

Unicode编码

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值