JS学习笔记:null与undefined区别

2022-05-13 17:02:01

相同点

nullundefined都可以表示“没有”,含义非常相似。将一个变量赋值为undefinednull,老实说,语法效果几乎没区别。在if语句中,它们都会被自动转为false,相等运算符(==)甚至直接报告两者相等。

//等同,下列式子返回truenull==undefined;

区别

1.类型不同

null在js中定义的对象,表示空对象,但undefined代表未定义;

//null为空对象typeof(null)//  "object"//未定义typeof(undefined)//"undefined"

2.转化不同

  当作数值类型进行转化时,null会被转为0,undefined会被转化为NaN

Number(null)// 05+null// 5Number(undefined)// NaN5+undefined// NaN

3.用法

  null表示空值,即该处的值现在为空。调用函数时,某个参数未设置任何值,这时就可以传入null,表示该参数为空。比如,某个函数接受引擎抛出的错误作为参数,如果运行过程中未出错,那么这个参数就会传入null,表示未发生错误。

  undefined表示“未定义”,通常变量或者对象声明了未被赋值,该变量或者对象就是undefined状态。下面是返回undefined的场景:

// 变量声明了,但没有赋值var i;
i// undefined// 调用函数时,应该提供的参数没有提供,该参数等于 undefinedfunctionf(x){return x;}f()// undefined// 对象没有赋值的属性var  o=newObject();
o.p// undefined// 函数没有返回值时,默认返回 undefinedfunctionf(){}f()// undefined
  • 作者:Saga Two
  • 原文链接:https://blog.csdn.net/m0_46309087/article/details/114532259
    更新时间:2022-05-13 17:02:01