1.字符串(string)转数值(numbe)

  1. var str = 10;
  2. var s ="hello";
  3. var t ="2222"
  4. // var num = Number(str);
  5. // console.log(num);
  6. console.log(Number(s));
  7. console.log(Number(t));
  1. 字符串转换为数值时,只有引号下为数字时,才能转换,否则输出为NaN

2.布尔型(boolean)转数值(number)

  1. var a = true;
  2. var b =false;
  3. console.log(Number(a));
  4. console.log(Number(b));
  1. 赋值为true时,转换为数值时,输出为1;赋值为false时,转换为数值,输出为0

3.数值(number)转布尔型(boolean)

  1. var a = 0;
  2. var b= 2;
  3. var c= 10;
  4. console.log(Boolean(a));
  5. console.log(Boolean(b));
  6. console.log(Boolean(c));
  1. number转布尔型时,只有当变量赋值为0时,为false,其他都为ture;

4.字符串(string)转布尔型(boolean)

  1. var str ="hello";
  2. var s = " ";
  3. var a ="";
  4. console.log(Boolean(str));
  5. console.log(Boolean(s));
  6. console.log(Boolean(a));
  1. 字符串转布尔型时,只有当引号内为空,输出为false,其他都为ture;

5.自动转换(算术,比较)

定义:不需要程序员干预,js自动完成的类型转换
算数计算中的自动转换:

5-1 -运算

在算术计算中先将数据转换为number,再计算

  1. var a = true;
  2. var b = "13";
  3. var c = b-a;
  4. // var c= Number(b)-Number(a);
  5. console.log(c);
  6. //输出为12

5-2 +运算

+运算中,只要有一边为字符串,那么结果一定字符串。+号起拼接符作用

  1. var a = true;
  2. var b = 10;
  3. var c = "1";
  4. console.log(a+b); //11
  5. console.log(b+c) //"101" c赋值为字符串,起拼接作用
  6. console.log(a-c) //0

5-3 比较运算

  1. var a = "hello";
  2. var b = true;
  3. var c = "10";
  4. console.log(a>b);//false NaN>1 NaN和任意值计算,结果都为NaN
  5. console.log(b>c); //false