美文网首页
null与undefined

null与undefined

作者: YoungEvita | 来源:发表于2018-07-26 09:03 被阅读0次
var a = undefined;
var b = null;

if (!a) {
    console.log('undefined is false'); // undefined is false
}
if (!b) {
    console.log('null is false'); // null is false
}

console.log(isNaN(a)); // true
console.log(isNaN(b)); // false
console.log(a == b); // true
console.log(a === b); // false
console.log(typeof null); // object
console.log(typeof undefined); // undefined
  • undefined与null转换为布尔值都为false;
  • null 表示一个“无”的对象,转为数值时为0;undefined表示一个“无”的原始值,转换为数字位NaN;
  • undefined 从null派生 “==”,认为相等所以输出true;“===”需要比较类型,类型不一致,所以输出false;

1、null 表示没有对象,即该出不应该有值,用法为:

① 作为函数的参数,表示该函数的参数不是对象。
② 作为对象原型链的终点。

2、undefined表示"缺少值",就是此处应该有一个值,但是还没有定义。典型用法是:

① 变量被声明了,但没有赋值时,就等于undefined。
② 调用函数时,应该提供的参数没有提供,该参数等于undefined。
③ 对象没有赋值的属性,该属性的值为undefined。
④ 函数没有返回值时,默认返回undefined。

// 变量声明未初始化
var a;
console.log(a); // undefined

// 函数调用未传参
function f(x) {
    console.log(x);
}
f(); // undefined

// 对象未赋属性值
var o = new Object();
console.log(o.p); // undefined

// 函数没有返回值
var x = f();
console.log(x); // undefined

参考资料
阮一峰-undefined与null的区别

相关文章

  • 02-相关问题

    undefined 与 null 的区别? undefined :代表定义未赋值 null :null 定义并赋值...

  • 随堂笔记

    undefined与null typeof undefined === 'undefined' typeof nu...

  • TypeScript 基础语法

    1、void 与 undefined和 null 与 void的区别是,undefined 和 null是所有类...

  • JS杂记

    1、Undefined 与 Null 的区别 Undefined 与 null 的值相等,但类型不相等。在js中,...

  • null与undefined

    undefined与null转换为布尔值都为false;null 表示一个“无”的对象,转为数值时为0;undef...

  • null 与 undefined

    undefined值是派生自null值 undefined:声明一个变量但未初始化,这个变量的值就自动被赋予und...

  • null与undefined

    一、相似性在JavaScript中,将一个变量赋值为undefined或null,老实说,几乎没区别。 上面代码中...

  • null 与 undefined

    null 表示一个对象的值是空值,而undefined 表示一个对象是没有被赋初值的。 好吧,这并没什么用。 按照...

  • undefined与null

    1.Undefined Undefined 类型只有一个值,即undefined。在使用var 声明变量但未对其初...

  • undefined 与 null

    undefined 与 null 都是 JavaScript 的基本数据类型,在转换为 Boolean 类型时也都...

网友评论

      本文标题:null与undefined

      本文链接:https://www.haomeiwen.com/subject/htkymftx.html