Samgao0312 / Blog

MIT License
1 stars 1 forks source link

【再学前端】null 和 undefined区别,应用场景? #146

Open Samgao0312 opened 2 years ago

Samgao0312 commented 2 years ago

null 和 undefined的区别

直接先上结论: null 和 undefined 基本相同,只有细微差别

//(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)作为[函数](https://www.fly63.com/tag/%E5%87%BD%E6%95%B0)的参数,表示该函数的参数不是对象。
- (2)作为对象原型链的终点。
- (3)如果定义的变量准备在将来用于保存对象,此时可以将该变量初始化为null
```js
// 作为函数的参数,表示该函数的参数不是对象
 function  add() {
     console.log(111)
 }
 add(null);

// 作为对象原型链的终点
console.log(Object.getPrototypeOf(Object.prototype));//null

// 定义的变量准备在将来用于保存对象
var a = null;

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