JavaScript 中的 null 是 js 中的 关键字,表示空值,null 可以看作是 was object 的一个特殊的值,如果一个 object 值为空,表示这个对象不是有效 对象。
undefined 不是 js 中的关键字,其是一个 全局变量,是 Global 的一个属性。
都是原始类型的值,保存在栈中变量本地。
调用函数时,该提供的参数没有提供,返回 undefined
<!DOCTYPE html>
<html>
<head>
<title>调用函数时,该提供的参数没有提供,返回 undefined</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
function func(a){
console.log(a);
}
func();
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们定义了一个函数 func,并且该函数接受一个 参数 a,接着,我们调用该函数但没有传入任何参数,结果返回了 undefined。
调用函数时,函数没有返回值时,返回 undefined
<!DOCTYPE html>
<html>
<head>
<title>调用函数时,函数没有返回值时,返回 undefined</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
function func(a){
console.log(a);
}
var a = func();
console.log('a =', a);
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们定义了一个函数 func,并且该函数没有任何返回值,接着,我们调用该函数时,我们使用了一个返回值接受函数的返回值,此时返回了 undefined。
JavaScript null是 Object 类型,undefined 是 undefined 类型
<!DOCTYPE html>
<html>
<head>
<title>JavaScript null是 Object 类型,undefined 是 undefined 类型</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
console.log("undefined type =", typeof(undefined));//undefined
console.log("null type =", typeof(null));//object
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们分别使用 typeof 获取了 undefined 的数据类型与 null 的数据类型,结果 undefined 返回了 undefined ,null 返回了 object。
JavaScript null 与 undefined 转换时值不一样
<!DOCTYPE html>
<html>
<head>
<title>JavaScript null 与 undefined 转换时值不一样</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
console.log("undefined number =", Number(undefined));//NaN
console.log("undefined number =", Number(10+undefined));//NaN
console.log("null number =", Number(null));//0
console.log("null number =", Number(10+null));//10
</script>
</head>
</html>
程序运行后,控制台输出如下:
使用 Number 转换 null 时,会返回 0,使用 Number 转换 undefined 时,返回 NaN。
使用 == 比较 null 与 undefined 相等,使用 === 比较 null 与 undefined 不相等
<!DOCTYPE html>
<html>
<head>
<title>使用 == 比较 null 与 undefined 相等,使用 === 比较 null 与 undefined 不相等</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
console.log("undefined === null is:", undefined === null);
console.log("undefined == null is:", undefined == null);
</script>
</head>
</html>
程序运行后,控制台输出如下:
使用 == 比较 null 与 undefined 相等,使用 === 比较 null 与 undefined 不相等。
JavaScript 中的 null 是 js 中的关键字,表示空值,null 可以看作是 object 的一个特殊的值,如果一个 object 值为空,表示这个对象不是有效对象。
undefined 不是 js 中的关键字,其是一个全局变量,是 Global 的一个属性。