JS-undefined/null
JS-undefined/null
- 同
- 异
- 转换成数字的时候
- 意义不同
- null表示该对象不存在
- undefined表示该变量已经定义但是没有值
- 例子
同
if 判断语句中,两者都会被转换为false
异
转换成数字的时候
null是一个表示无的对象,转换为数值为0;
undefined表示一个无的原始值,转化为数值为NAN(与任何数字相加也为NAN)
Number(null)输出为0, Number(undefined)输出为NaN
意义不同
null表示该对象不存在
1.作为函数的参数,表示该函数的参数不是对象
2.作为对象原型链的终点
undefined表示该变量已经定义但是没有值
情形如下
1.变量被声明了但是没赋值时
2.调用函数时,应该提供的参数没提供,则该参数为undefined
3.函数没有返回值时,默认返回undefined
4.对象没有赋值的属性
例子
/*以下例子均是在谷歌浏览器中的控制台中输出 第一行为待验证代码 第二行为结果*/
null
null
var hong;
undefined
//定义一个函数 可以通过shift + enter 不执行回车
function test(a) {
console.log(a);
}
undefined
//调用函数
test();
//输出没有定义
VM205:2 undefined
//返回没有定义
undefined
//调用没有定义的对象
var obj = {
};
undefined
obj.h;
undefined
//null的类型是对象
typeof null
"object"
//null和undefined是相等,毕竟undefined是从null派生出来的,所以把它们定义为相等的
null == undefined
true
//在一些情况下,我们一定要区分这两个值,那应该使用===不转换类型直接进行比较 或者使用typeof null == typeof undefined
null === undefined
false
//即使强制复制为null仍然会输出undefined
var n = null
undefined
//字符串与没有定义的直接相连会直接报错
'test'+abc
VM2380:1 Uncaught ReferenceError: abc is not defined
at <anonymous>:1:8
(anonymous) @ VM2380:1
//而如果跟未赋值的变量会出现直接加上undefined
'test'+undefined
"testundefined"
还没有评论,来说两句吧...