Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

null 和 undefined #156

Open
S-T-D opened this issue Sep 23, 2021 · 0 comments
Open

null 和 undefined #156

S-T-D opened this issue Sep 23, 2021 · 0 comments

Comments

@S-T-D
Copy link
Owner

S-T-D commented Sep 23, 2021

最初设计

JavaScript的最初版本是这样区分的:null是一个表示"无"的对象,转为数值时为0;undefined是一个表示"无"的原始值,转为数值时为NaN。 —— 《undefined与null的区别》

 

null

  • null 表示 空值、不存在的 或 不可用的值。
  • null 必须显式赋值。
    let a = null;
    console.log(a); // null
  • null 可以作为函数的参数,表示这个参数为空值,没有值。
    fs.readFile('someFile', 'utf8', (err, data) => {
        if (err) {
            // do something
        } else {
            // no error
        }
    });
  • null 作为原型链的终点。
    Object.getPrototypeOf(Object.prototype); // null

 

undefined

  • undefined 表示变量已经声明,但是还没有初始化。
  • 可以显式赋值也可以不显式赋值。
    let b;
    console.log(b); // undefined
  • 调用函数时,没有传对应的参数,那么这个参数在函数内部是 undefined
    function fn(name) {
        console.log(name);
    };
    
    fn();   // log: undefined
  • 访问对象不存在的属性,属性值为 undefined
  • 函数返回值默认为 undefined

 

相同点

  • 都属于基本数据类型。
  • 都是 “假” 值。
    Boolean(null) === Boolean(undefined)
  • == 比较时相等。
    null == undefined; // true

 

不同点

  • typeof 返回值不同。
    let a = null;
    let b;
    
    console.log(typeof a); // object
    
    console.log(typeof b); // undefined
  • === 比较时不相等。
    null !== undefined; // true
  • 传递给默认参数时。
    function test(name = 'xiaoming') {
        console.log(name);
    };
    
    test(null);         // null
    
    test(undefined);    // xiaoming
    
    test();             // xiaoming
  • json 序列化。
    JSON.stringify({name: null, age: undefined}); // {"name":null}

 

参考资料

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant