为什么 javascript 有 null 和 undefined?

dav*_*der 7 javascript

为什么javascript有nullundefined?它们似乎都意味着相同的事情,there's nothing here而且它们都应该是错误的。但这也意味着,例如,如果我要检查,如果事情存在,但它可能是{}[]0或其他一些falsey件事我必须检查

if(thing !== undefined && thing !== null)
Run Code Online (Sandbox Code Playgroud)

另外,我知道那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
Run Code Online (Sandbox Code Playgroud)

此外,undefined应该意味着尚未声明该变量,但您可以声明一个变量,如

const undefinedVariable = undefined;
Run Code Online (Sandbox Code Playgroud)

所以它已被定义但尚未被定义?

所以我要说的是虽然它们有不同的语义含义,一个表示一个尚未声明的变量,一个表示一个没有值的变量,它们似乎具有功能,但它们都是假的,试图获得一个属性形式他们会返回一个错误。

基本上我要问的是为什么我们需要两者,为什么不只使用像 pythonNone这样的语言或像 java 和 c++ 这样的低级语言Null

dba*_*tor 6

我建议您考虑一下他们的目的,以更好地理解其中的差异。

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

同时,任何尚未赋值的变量都是类型undefined。方法、语句和函数也可以返回undefinedundefined当你调用一个对象不存在的属性或方法时,你也会得到。

undefined与空值无关。例如:

console.log(5 + undefined);
// expected output: NaN
console.log(5 + null);
// expected output: 5
Run Code Online (Sandbox Code Playgroud)

考虑到 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
Run Code Online (Sandbox Code Playgroud)