!!和js数据类型的问题

①判断时为什么要加!!(!!就只应用于将类型转换为布尔值)?

	第一个!将除布尔以外的其他类型,隐式转换为布尔类型,
	使用!!可以判断变量的值,如果值为真,首先排除null和undefined
    然后根据类型判断:
     数值:不是0,有确切的值(包括无穷大)
     字符串:表示长度大于1
     数组,对象和函数无法判断
	 let a = null;
      let b = undefined;
      let c = 0;
      let d = " ";//非空字符串
      let e = [];
      let f = {};
      let g = "";//空字符串,转换为布尔值为false
      // true true true false false false
      console.log("!",!a,!b,!c,!d,!e,!f);  
      // false false false true true true
      console.log("!!",!!a,!!b,!!c,!!d,!!e,!!f);
      // object undefined number string object object
      console.log(typeof(a),typeof(b),typeof(c),typeof(d),typeof(e),typeof(f));
      // boolean boolean boolean boolean
      console.log(typeof(!a),typeof(!b),typeof(!c),typeof(!d),typeof(!e),typeof(!f));
      console.log(typeof(!!a),typeof(!!b),typeof(!!c),typeof(!!d),typeof(!!e),typeof(!!f));

作为条件表达式,不需要用!!进行转换

②JS数据类型转换(显式数据类型转换,隐式数据类型转换)
null、undefined、boolean、string、number、object

显式:
 1. Number
 2. parseInt()
 3. parseFloat();//浮点数(小数)
 4. String():
 5. toString()——无法转换null和undefined
 6. Boolean():

注意:在进行boolean转换的时候所有的内容在转换以后结果都是true,除了:false、""(空字符串)、0、NaN、undefined

隐式:
通常发生在运算符的加减乘除,等于、大于、小于等

猜你喜欢

转载自blog.csdn.net/weixin_42113124/article/details/83988393
今日推荐