null与undefined到底有啥区别?
2024-09-01 01:10:00
话不多说,直接先上结论: null
和 undefined
基本相同,只有细微差别
null
是表示缺少的标识,指示变量未指向任何对象,转为数值为0
undefined
表示 “缺少值”,即该处应该有值,但还没有定义,转为数值为NaN
//(1)null转为数值为0
console.log(Number(null));//0
console.log(null+3);//3
console.log(null == null);//true
console.log(null === null); //true
console.log(isNaN(null));false //(2)undefined转为数值为NaN
console.log(Number(undefined));//NaN(not a number)
console.log(3+undefined);//NaN
console.log(isNaN(undefined));//true //(3)null和undefined比较
console.log(null == undefined); //true,存在隐式类型转换
console.log(null === undefined);//false
/* "==="表示全等,二者类型不同,所以为false */
console.log(typeof null);//object数据类型
console.log(typeof undefined);//undefined数据类型
null 应用场景:
(1)作为函数的参数,表示该函数的参数不是对象
(2)作为对象原型链的终点
console.log(Object.getPrototypeOf(Object.prototype));//null
undefined 应用场景:
(1)一个没有被赋值的变量的类型是undefined
(2)调用函数时,应该提供的参数没有提供,该参数为undefined
(3)对象没有赋值的属性,该属性的值为undefined
(4)一个函数如果没有使用return语句指定返回值,就会返回undefined
//(1)变量未赋值
let a
console.log(a);//undefined //(2)函数参数未赋值
(function fn(x) {
console.log(x); //undefined
})() //(3)对象属性未赋值
let obj = {
name:'张三'
}
console.log(obj.name);
console.log(obj.age);//undefined //(4)函数没有返回值
function fn(){}
var x = fn();
console.log(x);//undefined
最新文章
- jQuery1.6源码分析系列
- 【转】如何配置android的adb环境变量
- npm配置文件
- 【GoLang】GoLang for 中有多个循环变量怎么处理?
- linux创建子进程--fork()方法
- laravel 指定 版本安装
- 学习angular 指令构造器时遇到的小问题
- 用bash命令得到Windows一个目录下的所有文件并且把结果输入到一个文件
- HDU 4746 Mophues 莫比乌斯反演
- c语言0 ‘0’ '\0'空格都是什么玩意儿
- PHP上传图片
- CreateFile,ReadFile等API详解(或者说MSDN的翻译)
- poi jsp xls
- Asp.net Core 跨域配置
- 真正理解拉格朗日乘子法和 KKT 条件
- MySql查询不区分大小写解决方案(两种)
- python学习---装饰器
- WPF-在Grid中编程添加控件
- thinkphp51初始化方法initialize
- (转)base64编码是怎么工作的?