javascript 中容易出错的知识点

  • undefined : 指从未赋值;
  • null : 指曾赋过值,但是目前没有值;
  • NaN : 无效数值,失败数值,指执行数学运算没有成功,这是失败返回的结果。NaN != NaN; 值为true,判断是否为NaN需要用 ES6 新增的 Number.isNaN( .. ) ,不能用window.isNaN( … ), 因为window.isNaN( ‘foo’ ) 值为true。

  • typeof null === 'object'; //true
  • typeof undefined === 'undefined'; //true
  • typeof有一个安全防范机制:
   var a;
   typeof a;  //undefined
   typeof b ;  //undefined

   a //undefined
   b //ReferenceError:b is not defined
   
  解释: undefined : 变量在未持有值的时候为 undefined;
  这里 b 的报错信息改成b is not declared会更准确.(declared:声明,defined:下定义) 

使用 typeof b === 'undefined'  可以在程序中用来判断变量是否存在。

如 
   if( b ){   //报错
   	console.log(b)
   }

   if( typeof b !== 'undefined'){  //安全
   	console.log(b)
   }
判断全局是否存在变量b也可以用 window.b 来进行,这样写也不会报错;
  • 字符串和数组相似,它们都是类数组,都有length属性以及indexOfconcat方法。但字符串不通过方法改变某个数值,而数组可以。
  • 42.toFixed(2) 无效,(42).toFixed(2);0.42.toFixed(2);42..toFixed(2);有效
  • 0.1 + 0.2 === 0.3 //值为 false,二进制浮点数中的0.1,0.2并不是十分精确,只是无限接近,0.1+0.2结果为0.3000000000000004。
发布了18 篇原创文章 · 获赞 10 · 访问量 611

猜你喜欢

转载自blog.csdn.net/llq886/article/details/105307718