javascript

null,undefined的区别?

2023-10-28  本文已影响0人  祈澈菇凉

在 JavaScript 中,null 和 undefined 都表示没有值或缺失值的状态,但它们之间有一些区别。

null:

null 是一个表示空值的特殊关键字。它是一个表示变量未赋值的值,可以将其赋给任何变量,表示该变量为空。使用 null 可以明确地将一个变量设置为空。

示例:

let myVariable = null;
console.log(myVariable); // 输出:null

可以看到,将变量赋值为 null 后,它的值确实为 null。

undefined:

undefined 是一个表示未定义值的全局属性。当变量已经声明但未赋值时,它的默认值就是 undefined。此外,在函数中没有返回值时,函数的返回值也是 undefined。

示例:

let myVariable;
console.log(myVariable); // 输出:undefined

function myFunction() {
  // 没有返回值,默认返回 undefined
}
console.log(myFunction()); // 输出:undefined

可以看到,在上述示例中,变量 myVariable 在声明时未赋值,因此它的值为 undefined。而函数 myFunction 没有显式返回值,因此其返回值为 undefined。

区别总结:

需要注意的是,在使用条件判断时,null 和 undefined 均被视为“假值”,即在条件判断中被认为是 false。例如:

let myVariable = null;
if (myVariable) {
  console.log("This will not be executed.");
} else {
  console.log("This will be executed."); // 输出:This will be executed.
}

尽管 myVariable 的值为 null,但在条件判断中被视为假值,因此执行了对应的代码块。

上一篇 下一篇

猜你喜欢

热点阅读