1、string、Boolean—>number

1-1 string—>number

  1. // tip:a.只能识别纯数字的字符串,其他字符输出NaN
  2. b.""," "识别成0
  3. c.parseInt("12px") parseFloat("12.123px")
  4. var str = "3";
  5. var num = Number(str);
  6. console.log(typeof num);
  7. console.log(Number("3.0"));
  8. console.log(Number("3.00"))
  9. console.log(Number("3px")) // NaN

1-2 boolean—>number

  1. var a= true;
  2. var b= false;
  3. console.log(Number(a))
  4. console.log(Number(b))

1-3 undefined,null和对象—>number

  1. undefined-->number //NaN
  2. null-->number //0
  3. 对象-->number //NaN
  1. 总结:
  2. (1)数字的转换结果有三种: 数字, 0 , NaN
  3. (2)其他类型转数字类型的时候, 就拿这三种结果区推断, 会是那一个

2 、string、number—>Boolean

  1. // string转化为Boolean
  2. // 特点:""为false,其他为true
  3. var str = "hello world"
  4. var s = " "
  5. var t = ""
  6. console.log(Boolean(str))
  7. console.log(Boolean(s))
  8. console.log(Boolean(t))
  9. // number转化为Boolean
  10. // 特点:0为false,其他为true
  11. var num = 2,m = -2,n = 0
  12. console.log(Boolean(num),Boolean(m),Boolean(n))
  1. 总结:
  2. - 转换方法 Boolean(变量)或者 !!变量
  3. - 意思上若包含'无','空'的时候转为false,其他为true
  4. - 对象全部为true

3、number、boolean转换为string

  1. var num = 1,boolean = false
  2. console.log(String(num))
  3. console.log(boolean.toString(num))

4、不是纯数字的字符串转换number

  1. /* 12px
  2. parseInt -- number
  3. parseFloat -- 小数点
  4. */
  5. console.log(parseInt("12px"))
  6. console.log(parseFloat("12.123px"))

5、undefined和NaN

  1. /*
  2. Number --> 0;
  3. string --> "";
  4. undefined
  5. NaN
  6. */
  7. var a;
  8. console.log(Boolean(a))
  9. // NaN
  10. console.log(Boolean(NaN))