null 和 undefined 的区别是什么?
请说明 JavaScript 中 null 和 undefined 的区别,及其使用场景。
回答
专业代码师
undefined:表示变量声明但未初始化,或访问对象不存在的属性。
- 使用场景:未赋值的变量、函数无 return 时、对象缺少的属性、数组越界访问
null:表示空引用,是一个表示"没有对象"的占位符。
- 使用场景:主动将变量置空、作为函数的参数表示无值、作为原型链终点(
Object.getPrototypeOf(Object.prototype))
区别:
typeof undefined→'undefined',typeof null→'object'(历史遗留 bug)undefined == null→true(宽松相等),undefined === null→falseNumber(undefined)→NaN,Number(null)→0JSON.stringify({a: undefined, b: null})→'{"b":null}'(undefined 被忽略)- 默认参数只在值为
undefined时生效:function f(x = 1) {}; f(undefined) // x=1; f(null) // x=null