1.将字符串类型转换为数值类型,然后参与运算
const num ="123";
console.log(num+3);//这里的+是字符串连接作用,输出1233
隐式转换为Number类型
console.log(num*1+3);//126
console.log(Number(num)+3);//126
2.parseFloat、parseInt
const num ="99.5jvjvgjj";
console.log(parseInt(num));//99
const num ="99.5jvjvgjj";
console.log(parseFloat(num));//99.5
3.字符串转化成数组(使用split)
const num ="99.5jvjvgjj";
console.log(num.split(""));// ["9", "9", ".", "5", "j", "v", "j", "v", "g", "j", "j"]//长度为11
4.数组转化成字符串(使用join)
const num =['hello',' world'];
console.log(num.join(""));//hello world,以空白连接
console.log(num.toString());//hello, world,以,连接
5.Boolean类型隐式转换
const bool = new Boolean(true);
console.log(bool);//Boolean {true},若想要拿到它的值可以使用valueOf()
console.log(bool.valueOf());//true
数值和boolean类型进行比较,他们都会转化成数值类型
true=》1 false=》0
console.log(false==89);//false
cosnole.log(true==1);//true
当数值单独为表达式的时候,除了0,其他都成立为true
const n = 0;
if(n){//此时为false,括号语句不执行
console.log('df')
}
if(8){//此时表达式为true,括号里的语句执行
console.log('df')
}
console.log('0'==false);//true
[]、{}转化成boolean类型都为true,引用类型都为true
console.log(Boolean({}))//true
console.log(Boolean([]))//true
if([]){//此时表达式为true
console.log('hhhhhh')
}
总结:数值类型除了0,其他都为true
字符串类型,除了空字符串,其他都为true
引用类型(数组、对象)都为true
显示转换Boolean类型(!!)
1.针对数值
const num = 0;
const bool = !!num;
console.log(bool);//false
Boolean(num);//false
2.针对字符串
let string = "helloworld";
console.log(!!string)//true
let string = "";
console.log(!!string)//false
3.针对数组和对象
let string = [];
console.log(!!string)//true
Number基本函数(isInteger,toFixed,isNaN)
let number = "99.99";
console.log(Number.isInteger(number));//false
console.log(9.032.toFixed(2));//9.03
console.log(9.039.toFixed(2))//9.04小数位留2位,其他四舍五入
let number = "99.99";
console.log(Number.isNaN(number))//false,因为99.99是数值类型
console.log(Object.is(number,NaN));//第二种书写方式