javascript
null 和 undefined 的区别
null 和 undefined 的共同点是它们都表示“无值”。
语义上的区别是 null 是“没有值,因为值本身不存在”,而 undefined 是“没有值,因为没有分配值”。
let name1 = null; // 明确指出的值为空时
console.log(name1); // null
let name2; // 申明但并未赋值
console.log(name2); // undefined
当访问对象上不存在的属性时undefined也会返回。
let user = {
name: 'John'
}
console.log(user.name); // "John" → name属性存在
console.log(user.age); // undefined → age属性不存在
运算符类型
使用 typeof 运算符检查数据类型 null 返回"object" ;而 undefined 还是 “undefined”
console.log(typeof null); // "object"
console.log(typeof undefined); // "undefined"
函数中参数为undefined时
function multiply(a, b) {
return a * b
}
multiply(5, 2) // 10
multiply(5) // NaN !
当函数没有指定返回值时,它会自动返回 undefined。
如果函数使用 return 关键字但没有指定返回值,则返回 null。
如果函数使用 return 关键字并指定 null 或 undefined 作为返回值,则返回相应的值。
// 如果不写函数的`return`返回值
function testFunc() {}
console.log(testFunc()); // undefined
// 调用带参数的函数时未给出参数时的值
function emptyFunc(param) {
console.log(param); // undefined
}
// 调用函数时未给参数
emptyFunc();