强制类型转换
一、其他数据类型 强制转换为 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