This question already has answers here:
What is the difference between null and undefined in JavaScript?

(35个答案)


在12个月前关闭。




为什么javascript有nullundefined?它们似乎都意味着同一件事,即there's nothing here,而且都应该是虚假的。但这意味着,例如,如果我要检查是否存在某些东西,但可能是{}[]0或我必须检查的其他虚假内容

if(thing !== undefined && thing !== null)

另外,我知道typeof nullObject,但是typeof {}也是Object,而typeof undefined"undefined",但是

const nullVariable = null;
console.log(nullVariable.x) // => error
const emptyVariable = {};
console.log(emptyVariable.x) // => undefined
const undefinedVariable;
console.log(undefinedVariable.x) // => error

同样,undefined应该意味着该变量尚未被声明,但是您可以声明一个变量,例如
const undefinedVariable = undefined;

因此已经定义但尚未定义?

所以我要说的是,虽然它们具有不同的语义含义,但是,这意味着尚未声明的变量,而在意味着没有值的变量,它们似乎具有功能,并且都为假,试图获取属性形式他们将返回错误。

基本上,我要问的是为什么我们同时需要这两个原因,为什么不只将pythont和None一起使用,又不将像java和c++这样的低级语言和Null一起使用?

最佳答案

我建议您考虑一下他们的目的,以便更好地理解它们之间的区别。

null表示任何对象值故意缺席。它永远不会由运行时分配。

同时,任何未分配值的变量的类型为undefined。方法,语句和函数也可以返回undefined。当您将称为对象的不存在的属性或方法时,也会得到undefined
undefined与空值无关。例如:

console.log(5 + undefined);
// expected output: NaN
console.log(5 + null);
// expected output: 5

鉴于JavaScript是动态类型化的,而对象是可以在运行时更改的属性的动态“包”,因此两者之间的区别很有用。
let car = {type: "Fiat", model:"500", color:"white"};
console.log(car.type);
// expected output: "Fiat"
console.log(car.price);
// expected output: undefined
car.price = null;
console.log(car.price);
// expected output: null
car.price = 2000;
console.log(car.price);
// expected output:2000

10-04 22:33
查看更多