网络课程教学平台seo基础培训教程
在 JavaScript 中,null 和 undefined 都表示没有值或缺失值的状态,但它们之间有一些区别。
null:
null 是一个表示空值的特殊关键字。它是一个表示变量未赋值的值,可以将其赋给任何变量,表示该变量为空。使用 null 可以明确地将一个变量设置为空。
示例:
let myVariable = null;
console.log(myVariable); // 输出:null
可以看到,将变量赋值为 null 后,它的值确实为 null。
undefined:
undefined 是一个表示未定义值的全局属性。当变量已经声明但未赋值时,它的默认值就是 undefined。此外,在函数中没有返回值时,函数的返回值也是 undefined。
示例:
let myVariable;
console.log(myVariable); // 输出:undefinedfunction myFunction() {// 没有返回值,默认返回 undefined
}
console.log(myFunction()); // 输出:undefined
可以看到,在上述示例中,变量 myVariable 在声明时未赋值,因此它的值为 undefined。而函数 myFunction 没有显式返回值,因此其返回值为 undefined。
区别总结:
- null 是一个表示空值的关键字,可以将其赋给任何变量,明确将其设置为空。
- un