1.字符串(string)转数值(numbe)
var str = 10;
var s ="hello";
var t ="2222"
// var num = Number(str);
// console.log(num);
console.log(Number(s));
console.log(Number(t));
字符串转换为数值时,只有引号下为数字时,才能转换,否则输出为NaN
2.布尔型(boolean)转数值(number)
var a = true;
var b =false;
console.log(Number(a));
console.log(Number(b));
赋值为true时,转换为数值时,输出为1;赋值为false时,转换为数值,输出为0
3.数值(number)转布尔型(boolean)
var a = 0;
var b= 2;
var c= 10;
console.log(Boolean(a));
console.log(Boolean(b));
console.log(Boolean(c));
number转布尔型时,只有当变量赋值为0时,为false,其他都为ture;
4.字符串(string)转布尔型(boolean)
var str ="hello";
var s = " ";
var a ="";
console.log(Boolean(str));
console.log(Boolean(s));
console.log(Boolean(a));
字符串转布尔型时,只有当引号内为空,输出为false,其他都为ture;
5.自动转换(算术,比较)
定义:不需要程序员干预,js自动完成的类型转换
算数计算中的自动转换:
5-1 -运算
在算术计算中先将数据转换为number,再计算
var a = true;
var b = "13";
var c = b-a;
// var c= Number(b)-Number(a);
console.log(c);
//输出为12
5-2 +运算
+运算中,只要有一边为字符串,那么结果一定字符串。+号起拼接符作用
var a = true;
var b = 10;
var c = "1";
console.log(a+b); //11
console.log(b+c) //"101" c赋值为字符串,起拼接作用
console.log(a-c) //0
5-3 比较运算
var a = "hello";
var b = true;
var c = "10";
console.log(a>b);//false NaN>1 NaN和任意值计算,结果都为NaN
console.log(b>c); //false