null 和 undefined的区别

188 阅读1分钟

null 和 undefined的区别

1.定义区分理解:

- null: 设为值null,即是将一个对象人为重置为空对象。而非一个对象最原始状态。
- undefined: 表示一个对象最原始状态,未人为赋值给该对象。

2.作为值时:

  - null: 就是空。null不是对象,且在栈中指针不指向堆中任何有效对象。
  - undefined: 应该有值但是没值。不是一个确切的值。
     - 定义变量但未赋值:let data;
     - 函数有参但未传参:
        getData(pagesize: bumber){
            console.log(pagesize); 
            return//此处应有返回值,但没有时,默认返回undefined;
        }
        getData(); 
        // 调用getData函数但未传参;打印获取pagesize值为undefined;
     - 访问对象上不存在的属性:
       console.log(Object.aaa) // undefined;

3.转化判断值时:

 - null ? true : false;        // false;
 - undefined ? true : false;   // false;
 
 - Number(null);               // 0 number类型;
 - Number(undefined);          // NaN;
 
 - typeof undefined            // 'undefined'
 - typeof null                 // 'Object' 
 typeof null实际不是Object类型,这只是 JavaScript 早期设计遗留下来的`BUG`且一直未得到修复

 

参考链接:

相关链接1 相关链接2 typeof null