详解undefined和null"/>
详解undefined和null
详解undefined
和null
-
出现
undefined
的几种场景// 1. 定义了但没有赋值 let a; console.log(a); // undefined// 2. 定义了但赋了一个空值 let obj = {} console.log(obj.name); // undefined// 3. 定义了一个函数但是没有返回值 function Fn() {} console.log(Fn()); // undefined// 4. 定义了一个函数,但是调用的时候只传递了第一个参数 function Fn2(p1,p2) {console.log(p2); } Fn2(1) // undefined
-
null
出现的场景几种场景let obj2 = null; //设置为null,是为了在以后的某个场景下进行再赋值 function Fn3() {return {} } obj2 = Fn3() // 2. 获取一个不存在的值 document.querySelector('#id') //null// 3.正则表达式 'test'.match(/a/) // null
-
undefined
和null
相同点和不同点
-
相同点:
-
一个对象字面量值 小写的
undefined
和null
-
undefined
和null
的布尔类型都是false
所以undefined
和!null
=true
他们两个就无法通过!判断区分undefined
和null
-
前端常见的
undefined
和null
的异常Uncaught TypeError: Cannot read properties of undefined (reading 'name') at <anonymous>:1:15
Uncaught TypeError: Cannot read properties of null (reading 'age') at <anonymous>:1:15
-
在非严格模式的比较下
undefiend
和null
是相等的console.log(undefined == null); // trueconsole.log(undefined === null); // false
-
-
不同点:
-
null
是javascript
的关键字undefined
是javascript
的一个全局变量 在浏览器下是挂载在window
对象下的console.log(window.undefined); // undefined
-
类型不同
undefined
的数据类型是undefined
null
的数据类型是object
-
call
函数调用toString
函数时Object.prototype.toString.call(null) // [object Null] Object.prototype.toString.call(undefined) // [object Undefined]
-
字符串类型转换 转换成本身字符串的转换形式
console.log(null + 'string'); //'nullstring' console.log(undefined + 'string'); //'undefinedstring'
-
参与运算的时候,
null
会转换为0
来运算,undefined
会转换成NaN
来运算console.log(null + 1) // 1 console.log(undefined + 1) //NaN
-
无论什么情况下,没有必要将一个变量显示为
undefined
,如果需要将某个变量将来用来保存某个数值,将其赋值为null
-
更多推荐
详解undefined和null
发布评论