如何区分null和undefined

null和undefined是两种数据类型, 如果硬要区分的话。

null是一种类型, 赋值变量为null型。

未定义的变量, 即为undefined。

var a = null
a  // null
var b
b  // undefined
typeof(b)  // "undefined"

标准解释

6.1.1 The Undefined Type
The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.

6.1.2 The Null Type
The Null type has exactly one value, called null.

undefined使用场景:

  • 判断变量, 判断函数传参异常, 判断对象字段和方法是否存在(或者正确使用Object.propretype.call(ob, 'key'))
  • es6中应对eslint规范的export default undefined

猜你喜欢

转载自www.cnblogs.com/daaasheng/p/9962668.html