JavaScript中的null和undefined


1.概述

  null和undefined属于js中两种不同的基本数据类型,都可以表示“没有”,含义非常相似。将一个变量赋值为undefined或null,老实说,语法效果几乎没区别。并且在if语句的判断条件中,它们都会自动转为false,相等运算符(==)甚至直接报告两者相等

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

  null是一个表示“空”的对象,转为数值时为0;undefined是一个表示"此处无定义"的原始值,转为数值时为NaN。

Number(null); // 0
null + 9; // 9
Number(undefined); // NaN
undefined + 9; // NaN

2.用法和含义

  对于null和undefined,大致可以像下面这样理解。null表示空值,即该处的值现在为空。调用函数时,某个参数未设置任何值,这时就可以传入null,表示该参数为空。比如,某个函数接受引擎抛出的错误作为参数,如果运行过程中未出错,那么这个参数就会传入null,表示未发生错误。undefined表示“未定义”,下面是返回undefined的典型场景。

// 变量声明了,但没有赋值
var i; i // undefined

// 调用函数时,应该提供的参数没有提供,该参数等于 undefined
function f(x) { return x; } f() // undefined

// 对象没有赋值的属性
var  o = new Object(); o.p // undefined

// 函数没有返回值时,默认返回 undefined
function f() {} f() // undefined

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM