为什么 null 是一个对象,null 和 undefined 有什么区别?

发布于 2024-07-18 08:43:19 字数 305 浏览 9 评论 0原文

为什么 JavaScript 中 null 被视为 object

检查

if ( object == null )
      Do something

与 一样吗

if ( !object )
      Do something

另外:

nullundefined 之间有什么区别?

Why is null considered an object in JavaScript?

Is checking

if ( object == null )
      Do something

the same as

if ( !object )
      Do something

?

And also:

What is the difference between null and undefined?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

爱你是孤单的心事 2024-07-25 08:43:20

什么是类型?

类型是对值进行分类的一种方式。。 这是一个表格,其中包含相关类型及其 typeof 结果。

类型值类型包含typeof 结果typeof 结果是谎言吗?
仅未定义undefined"undefined"
仅空null"object"
Object无限数量的值: {}, {a: "b"}, ..."object"没有

null不是一个对象,它的值类型为 Null。

typeof 运算符在说谎! 它为 null 返回 "object" 是 JavaScript 语言中的一个错误。

我在我的开源电子书中写了一个关于此的章节。 您可以在这里阅读https://github.com/carltheperson/advanced-js-objects

What is a type?

A type is a way to categorize values. Here is a table with the types in question and their typeof result.

TypeValues type containstypeof resultIs typeof result a lie?
UndefinedOnly: undefined"undefined"No
NullOnly: null"object"Yes
ObjectInfinite amount of values: {}, {a: "b"}, ..."object"No

null is not an object, its a value of type Null.

The typeof operator is lying! It returning "object" for null is a mistake in the JavaScript language.

I wrote a chapter about this in my open-source e-book. You can read it here https://github.com/carltheperson/advanced-js-objects

苏辞 2024-07-25 08:43:20

看这个:

function f(a){
  console.log(typeof(a));
  if (a==null) console.log('null');
  a ? console.log(true) : console.log(false);
}
        //return:
f()     //undefined    null    false
f(null) //object       null    false
f('')   //string               false
f(0)    //number               false
f(1)    //number               true
f('x')  //string               true
.as-console-wrapper { max-height: 100% !important; }

Look at this:

function f(a){
  console.log(typeof(a));
  if (a==null) console.log('null');
  a ? console.log(true) : console.log(false);
}
        //return:
f()     //undefined    null    false
f(null) //object       null    false
f('')   //string               false
f(0)    //number               false
f(1)    //number               true
f('x')  //string               true
.as-console-wrapper { max-height: 100% !important; }

我的影子我的梦 2024-07-25 08:43:20

null 是一个对象。 它的类型为空。 undefined 不是一个对象; 它的类型是未定义的。

null is an object. Its type is null. undefined is not an object; its type is undefined.

几度春秋 2024-07-25 08:43:20

与 undefined 相比,null 的另一个有趣之处在于它可以递增。

x = undefined
x++
y = null
y++
console.log(x) // NaN
console.log(y) // 0

这对于设置计数器的默认数值很有用。 您在变量声明中将变量设置为 -1 有多少次?

The other fun thing about null, compared to undefined, is that it can be incremented.

x = undefined
x++
y = null
y++
console.log(x) // NaN
console.log(y) // 0

This is useful for setting default numerical values for counters. How many times have you set a variable to -1 in its declaration?

风尘浪孓 2024-07-25 08:43:20
  1. Undefine 表示变量已被声明,但尚未被赋值,而 Null 可以被赋值给代表“无值”的变量。(Null 是赋值运算符)

2.Undefine 本身是类型,而 Null 是对象。

3.Javascript本身可以将任何未分​​配的变量初始化为未定义,但它永远不能将变量的值设置为null。 这必须以编程方式完成。

  1. Undefined means a variable has been declared but it has not been assigned any value while Null can be assigned to a variable representing "no value".(Null is an assignment operator)

2.Undefined is a type itself while Null is an object.

3.Javascript can itself initialize any unassigned variable to undefined but it can never set value of a variable to null. This has to be done programatically.

像你 2024-07-25 08:43:20

使用 null 将某些内容定义为没有值,当您期望某些内容可能根本没有定义时,使用 undefined 。

例如,如果变量没有值,则将其指定为 null。

var weDontHaveAValue = null;

如果您预计某些内容可能根本未定义,例如可选选项参数,请使用 undefined。

if (typeof args.optionalParam !== 'undefined') { }

Use null to define something as having no value, use undefined when you expect something might not be defined at all.

For example, if a variable has no value, assign it as null.

var weDontHaveAValue = null;

If you expect that something might be not defined at all, e.g. an optional options argument, use undefined.

if (typeof args.optionalParam !== 'undefined') { }
难得心□动 2024-07-25 08:43:20

console

未定义未定义并不是同一件事。

age;

您:年龄的值是多少?

计算机:好的,让我检查我的内存/参考表......此时(您询问的时间),我没有看到任何名为 age 的标识符,不在这个范围/上下文中或任何父范围/上下文; 我不知道年龄。 也许稍后我会遇到一条将该标识符添加到内存中的指令,但它现在不存在。

var age;

你:age的值是多少;

计算机:好的,检查我的内存...我在参考表中看到一个名为 age 的标识符,但在我添加它时没有值或指针或任何内容分配给它,所以我不知道不知道; 你可以认为它(age)是空的/什么都没有/无用的。

var age = null;

你:age的值是多少;

计算机:好的,检查我的记忆...我在参考表中看到age:它为空。 基本上,它什么都没有/空,你不能用这个值做任何事情; 这是故意的。

现在,我可能不应该这样解释,但希望它能有意义。

我明白为什么 null 被设计为 JS 中的对象,我个人喜欢这样。

nullundefined practically 表示同一件事:空/什么都没有。 区别在于它在概念上的使用方式。

我将 null 视为开发人员意图的虚无; 某些东西为空是故意做的,不代表任何东西。 我将未定义视为计算机意图的虚无; 开发者/用户意外地没有价值的东西。

例如,如果您从库/sdk 调用函数并返回 null,则几乎可以确定这是开发人员/作者故意设计的; 他们特别想表明虚无。

另请参阅 - https://developer.mozilla.org /en-US/docs/Web/JavaScript/Reference/Operators/null

console

Not defined and undefined are not the same thing happening.

age;

You: What is the value of age?

Computer: Okay, let me check my memory/reference table..... at this point (the time of you asking), i do not see any identifier named age, not in this scope/context or any parent scope/context; age is not known to me. Maybe later i will come across an instruction to add that identifier to memory, but it does not exist right now.

var age;

You: What is the value of age;

Computer: Okay, checking my memory... I see an identifier in my reference table with that name age but no value or pointer or anything was assigned to it at the time i added it, so i don't know; you can consider it (age) empty/nothing/useless.

var age = null;

You: What is the value of age;

Computer: Okay, checking my memory... i see age in my reference table: it is null. Basically, it is nothing/empty, you cannot do anything with this value; this was intentional.

Now, i probably should not explain it this way but hopefully it will make sense.

I can see why null was designed to be an object in JS, and i personally like it that way.

null and undefined practically means the same thing: empty/nothing. The difference is in how it is used conceptually.

I look at null as developer-intended nothingness; something being null was done on purpose to represent nothing. I look at undefined as computer-intended nothingness; something not having value by accident of the developer/user.

For example, if you call a function from a library/sdk and got back null, you can almost be sure that was designed on purpose by the developer/author; they specifically wanted to indicate nothingness.

Also see - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null

迷乱花海 2024-07-25 08:43:20

null 和 undefined 的主要区别在于 null 代表
丢失的对象,而 undefined 表示变量的未初始化状态。

您可以将 null 视为未定义的对象,但 undefined 只会是未定义的
因为它的类型是未定义的。

let a; 
console.log(a); //undefined, since it is declared but not initialized

console.log(null == undefined) //true
console.log(null === undefined) // false

console.log(typeof null) //object
console.log(typeof undefined) //undefined

The main difference between null and undefined is that null represents
a missing object, while undefined represents an uninitialized state of a variable.

You can think of null as an undefined object but undefined will be undefined only
since its type is undefined.

let a; 
console.log(a); //undefined, since it is declared but not initialized

console.log(null == undefined) //true
console.log(null === undefined) // false

console.log(typeof null) //object
console.log(typeof undefined) //undefined
独享拥抱 2024-07-25 08:43:19
(name is undefined)

您:名字是什么? (*)
JavaScript: 名称名称是什么? 我不知道你在说什么。 您之前从未提及过任何名字。 您是否在(客户端)看到其他脚本语言?

name = null;

你:名字是什么?
JavaScript:我不知道。

简而言之; 未定义是指不存在该事物的概念; 它没有类型,并且之前从未在该范围内被引用过; null 是已知该事物存在的位置,但不知道该事物的值是什么。

要记住的一件事是,从概念上讲,nullfalse"" 等不同,即使它们在类型转换后相等,即

name = false;

您:名字是什么?
JavaScript: 布尔值 false。

name = '';

你:名字是什么?
JavaScript: 空字符串


*: name 在此上下文中表示从未定义过的变量。 它可以是任何未定义的变量,但是,名称几乎是任何 HTML 表单元素的属性。 它的历史可以追溯到很久以前,并且早在 id 之前就已经制定了。 它很有用,因为 id 必须是唯一的,但名称不必如此。

(name is undefined)

You: What is name? (*)
JavaScript: name? What's a name? I don't know what you're talking about. You haven't ever mentioned any name before. Are you seeing some other scripting language on the (client-)side?

name = null;

You: What is name?
JavaScript: I don't know.

In short; undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it's not known what the value is.

One thing to remember is that null is not, conceptually, the same as false or "" or such, even if they equate after type casting, i.e.

name = false;

You: What is name?
JavaScript: Boolean false.

name = '';

You: What is name?
JavaScript: Empty string


*: name in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be.

妞丶爷亲个 2024-07-25 08:43:19

差异可以总结为以下代码片段:

alert(typeof(null));      // object
alert(typeof(undefined)); // undefined

alert(null !== undefined) //true
alert(null == undefined)  //true

检查

object == null 与检查 if (!object ) 不同。

后者等于! Boolean(object),因为一元 ! 运算符会自动将右侧操作数转换为布尔值。

由于 Boolean(null) 等于 false,因此 !false === true

因此,如果您的对象not nullbutfalse0"" ,检查将通过
因为:

alert(Boolean(null)) //false
alert(Boolean(0))    //false
alert(Boolean(""))   //false

The difference can be summarized into this snippet:

alert(typeof(null));      // object
alert(typeof(undefined)); // undefined

alert(null !== undefined) //true
alert(null == undefined)  //true

Checking

object == null is different to check if ( !object ).

The latter is equal to ! Boolean(object), because the unary ! operator automatically cast the right operand into a Boolean.

Since Boolean(null) equals false then !false === true.

So if your object is not null, but false or 0 or "", the check will pass
because:

alert(Boolean(null)) //false
alert(Boolean(0))    //false
alert(Boolean(""))   //false
萌酱 2024-07-25 08:43:19

null不是一个对象,它是一个原始值。 例如,您不能向其添加属性。 有时人们错误地认为它是一个对象,因为typeof null返回“object”。 但这实际上是一个错误(甚至可能在 ECMAScript 6 中修复)。

nullundefined 之间的区别如下:

  • undefined:由 JavaScript 使用,表示“无值”。 未初始化的变量、缺失的参数和未知的变量都具有该值。

    <前><代码>> var noValueYet;
    > console.log(noValueYet);
    不明确的

    > 函数 foo(x) { console.log(x) }
    > foo()
    不明确的

    > var obj = {};
    > console.log(obj.unknownProperty)
    不明确的

    但是,访问未知变量会产生异常:

    <前><代码>> 未知变量
    ReferenceError:未知变量未定义

  • null:程序员使用它来指示“无值”,例如作为函数的参数。

检查变量:

console.log(typeof unknownVariable === "undefined"); // true

var foo;
console.log(typeof foo === "undefined"); // true
console.log(foo === undefined); // true

var bar = null;
console.log(bar === null); // true

作为一般规则,在 JavaScript 中应始终使用 === 而决不使用 ==(== 执行 各种可能产生意外结果的转换)。 检查 x == null 是一种边缘情况,因为它适用于 nullundefined

> null == null
true
> undefined == null
true

检查变量是否已定义的常见方法a value就是将其转换为boolean,看是否为true。 该转换由 if 语句和布尔运算符 ! (“不是”)。

function foo(param) {
    if (param) {
        // ...
    }
}
function foo(param) {
    if (! param) param = "abc";
}
function foo(param) {
    // || returns first operand that can't be converted to false
    param = param || "abc";
}

这种方法的缺点:以下所有值都计算为 false,因此您必须小心(例如,上述检查无法区分 undefined0)。

  • 未定义null
  • 布尔值:false
  • 数字:+0-0、< code>NaN
  • 字符串:""

您可以通过使用 Boolean 作为函数来测试布尔值的转换(通常它是一个构造函数,与 <代码>新):

> Boolean(null)
false
> Boolean("")
false
> Boolean(3-3)
false
> Boolean({})
true
> Boolean([])
true

null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null returns "object". But that is actually a bug (that might even be fixed in ECMAScript 6).

The difference between null and undefined is as follows:

  • undefined: used by JavaScript and means “no value”. Uninitialized variables, missing parameters and unknown variables have that value.

    > var noValueYet;
    > console.log(noValueYet);
    undefined
    
    > function foo(x) { console.log(x) }
    > foo()
    undefined
    
    > var obj = {};
    > console.log(obj.unknownProperty)
    undefined
    

    Accessing unknown variables, however, produces an exception:

    > unknownVariable
    ReferenceError: unknownVariable is not defined
    
  • null: used by programmers to indicate “no value”, e.g. as a parameter to a function.

Examining a variable:

console.log(typeof unknownVariable === "undefined"); // true

var foo;
console.log(typeof foo === "undefined"); // true
console.log(foo === undefined); // true

var bar = null;
console.log(bar === null); // true

As a general rule, you should always use === and never == in JavaScript (== performs all kinds of conversions that can produce unexpected results). The check x == null is an edge case, because it works for both null and undefined:

> null == null
true
> undefined == null
true

A common way of checking whether a variable has a value is to convert it to boolean and see whether it is true. That conversion is performed by the if statement and the boolean operator ! (“not”).

function foo(param) {
    if (param) {
        // ...
    }
}
function foo(param) {
    if (! param) param = "abc";
}
function foo(param) {
    // || returns first operand that can't be converted to false
    param = param || "abc";
}

Drawback of this approach: All of the following values evaluate to false, so you have to be careful (e.g., the above checks can’t distinguish between undefined and 0).

  • undefined, null
  • Booleans: false
  • Numbers: +0, -0, NaN
  • Strings: ""

You can test the conversion to boolean by using Boolean as a function (normally it is a constructor, to be used with new):

> Boolean(null)
false
> Boolean("")
false
> Boolean(3-3)
false
> Boolean({})
true
> Boolean([])
true
情绪 2024-07-25 08:43:19

null 和 undefined 有什么区别?

没有定义的属性是未定义null 是一个对象。 它的类型是对象。 null 是一个特殊值,意思是“没有值。undefined 不是一个对象,它的类型是未定义的。

您可以声明一个变量,将其设置为 null,行为是相同的,只是您会看到打印出“null”与“您甚至可以将未定义的变量与 null 进行比较,反之亦然,条件将为 true:

 undefined == null
 null == undefined

请参阅 JavaScript null 和 undefined 之间的差异了解更多详细信息。

并使用新的编辑 yes

if (object == null)  does mean the same  if(!object)

当测试 if object 为 false 时,它​​们都只满足测试 if false 时的条件,而当测试 true 时则不满足

这里检查:Javascript 陷阱

What is the difference between null and undefined??

A property when it has no definition is undefined. a null is an object. Its type is object. null is a special value meaning "no value. undefined is not an object, its type is undefined.

You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". You can even compare a variable that is undefined to null or vice versa, and the condition will be true:

 undefined == null
 null == undefined

Refer to JavaScript Difference between null and undefined for more detail.

and with your new edit yes

if (object == null)  does mean the same  if(!object)

when testing if object is false, they both only meet the condition when testing if false, but not when true

Check here: Javascript gotcha

寻找一个思念的角度 2024-07-25 08:43:19

问题的第一部分:

为什么 null 在 JavaScript 中被视为对象?

这是一个 JavaScript 设计错误,他们现在无法修复。 它应该是 null 类型,而不是 object 类型,或者根本没有。 在检测真实对象时需要进行额外的检查(有时会被遗忘),并且是错误的根源。

问题的第二部分:

正在检查

if(对象== null)
做某事


相同

if (!object)
做某事

这两个检查始终都是 false,除了:

  • 对象未定义或 null:均为 true。

  • 对象是原始的,并且 0、"" 或 false:首先检查 false,第二个检查 true。

如果对象不是基元,而是真实对象,例如 new Number(0)new String("")new Boolean(false),那么两个检查都是假的。

因此,如果“对象”被解释为真正的对象,那么两个检查总是相同的。 如果允许原语,则对 0、"" 和 false 的检查会有所不同。

在诸如 object==null 的情况下,不明显的结果可能是错误的根源。 不建议使用 ==,而是使用 ===

问题的第三部分:

还有:

空和未定义有什么区别?

在 JavaScript 中,一个区别是 null 是 object 类型,而 undefined 是 undefined 类型。

在 JavaScript 中,null==undefined 为 true,如果类型被忽略,则被视为相等。 为什么他们这么决定,但 0、"" 和 false 不相等,我不知道。 这似乎是一种武断的意见。

在 JavaScript 中,null===undefined 不为 true,因为 === 中的类型必须相同。

实际上,null 和 undefined 是相同的,因为它们都代表不存在。 0 和 "" 也是如此,也许还有空容器 []{}。 如此多类型的相同内容会导致错误。 一种或根本没有更好。 我会尝试尽可能少地使用。

“假”、“真”和“!” 是另一堆可以简化的蠕虫,例如,单独使用 if(!x)if(x) 就足够了,不需要 true 和 false。

如果没有给出值,则声明的 var x 是未定义类型,但它应该与 x 从未声明过一样。 另一个错误来源是一个空的空容器。 所以最好是一起声明和定义,如var x=1

人们兜圈子,试图弄清楚所有这些不同类型的虚无,但它们只是穿着复杂的不同衣服的同一件事。 现实是

undefined===undeclared===null===0===""===[]==={}===nothing

也许所有人都应该抛出异常。

First part of the question:

Why is null considered an object in JavaScript?

It is a JavaScript design error they can't fix now. It should have been type null, not type object, or not have it at all. It necessitates an extra check (sometimes forgotten) when detecting real objects and is source of bugs.

Second part of the question:

Is checking

if (object == null)
Do something

the same as

if (!object)
Do something

The two checks are always both false except for:

  • object is undefined or null: both true.

  • object is primitive, and 0, "", or false: first check false, second true.

If the object is not a primitive, but a real Object, like new Number(0), new String(""), or new Boolean(false), then both checks are false.

So if 'object' is interpreted to mean a real Object then both checks are always the same. If primitives are allowed then the checks are different for 0, "", and false.

In cases like object==null, the unobvious results could be a source of bugs. Use of == is not recommended ever, use === instead.

Third part of the question:

And also:

What is the difference between null and undefined?

In JavaScript, one difference is that null is of type object and undefined is of type undefined.

In JavaScript, null==undefined is true, and considered equal if type is ignored. Why they decided that, but 0, "" and false aren't equal, I don't know. It seems to be an arbitrary opinion.

In JavaScript, null===undefined is not true since the type must be the same in ===.

In reality, null and undefined are identical, since they both represent non-existence. So do 0, and "" for that matter too, and maybe the empty containers [] and {}. So many types of the same nothing are a recipe for bugs. One type or none at all is better. I would try to use as few as possible.

'false', 'true', and '!' are another bag of worms that could be simplified, for example, if(!x) and if(x) alone are sufficient, you don't need true and false.

A declared var x is type undefined if no value is given, but it should be the same as if x was never declared at all. Another bug source is an empty nothing container. So it is best to declare and define it together, like var x=1.

People are going round and round in circles trying to figure out all these various types of nothing, but it's all just the same thing in complicated different clothes. The reality is

undefined===undeclared===null===0===""===[]==={}===nothing

And maybe all should throw exceptions.

沉睡月亮 2024-07-25 08:43:19

TLDR

undefined 是 JavaScript 中的一个原始值,表示隐式缺少某个值。 未初始化的变量自动具有此值,并且没有显式 return 语句的函数将返回 undefined

null 也是 JavaScript 中的原始值。 它表示故意缺少对象值。 JavaScript 中的 null 旨在实现与 Java 的互操作性。

typeof null 返回 "object",因为该语言的设计具有特殊性,源于 JavaScript 与 Java 互操作的要求。 这并不意味着 null 是对象的实例。 这意味着:给定 JavaScript 中的原始类型树,null 是“对象类型原始”子树的一部分。 下面对此进行更全面的解释。

详细信息

undefined 是一个原始值,表示 隐式缺少值。 请注意,直到 1998 年的 JavaScript 1.3。这告诉我们 null 旨在成为程序员在明确指示不存在值时使用的值。 未初始化的变量自动具有值undefinedundefined 是一个one-of-a- ECMAScript 规范中的 kind 类型

null 是一个原始值,表示有意缺少一个对象值。 null 也是一个 one-of-a ECMAScript 规范中的-kind 类型

JavaScript 中的 null 旨在实现与 Java 的互操作性,无论是从“外观”角度还是从编程角度(例如计划于 1996 年推出的 LiveConnect Java/JS 桥) )。 此后,布伦丹·艾奇 (Brendan Eich) 和其他人都对包含两个“缺乏价值”的价值观表示厌恶,但在 1995 年,艾奇奉命“让 [JavaScript] 看起来像 Java”。

布伦丹·艾奇

如果管理层没有向我发出“让它看起来像 Java”的命令,
并且我有更多的时间(很难区分这两个因果因素),那么我会更喜欢像自我一样的“一切都是对象”
方法:没有布尔、数字、字符串包装器。 没有未定义和空。
叹息。

为了适应 Java 的 null 概念,由于 Java 的强类型特性,它只能分配给类型为引用类型(而不是基元)的变量,Eich 选择将特殊的 < code>null 值位于对象原型链的顶部(即引用类型的顶部),并将 null 类型包含为“对象类型原语”集合的一部分”。

此后不久添加了 typeof 运算符 在 JavaScript 1.1 中,于 1996 年 8 月 19 日发布。

来自 V8 博客

typeof null 返回 object,而不是 null,尽管 null 是一个
自己的类型。 要理解原因,请考虑所有的集合
JavaScript 类型分为两组:

  1. 对象(即对象类型)
  2. 基元(即任何非对象值)

因此,null 表示“没有对象值”,而 undefined 表示“没有对象值”
值”。

在此输入图像描述

按照这个思路,Brendan Eich 设计了 ​​JavaScript
typeof 对于右侧的所有值返回“object”,
即所有对象和空值,本着 Java 的精神。 这就是为什么
typeof null === 'object' 尽管规范具有单独的 null 类型。

在此输入图像描述

因此,Eich 设计了基本类型的层次结构,以实现与 Java 的互操作性。 这导致他将 null 与“对象类型原语”一起定位在层次结构上。 为了反映这一点,当 typeof 添加到该语言后不久,他选择 typeof null 返回 “object”

JavaScript 开发人员在 typeof null === "object" 中表达的惊讶是同时具有 null 的弱类型语言 (JavaScript) 之间阻抗不匹配(或抽象泄漏)的结果undefined,以及另一种只有 null 的强类型语言 (Java),其中 null严格定义来引用引用类型(不是原始类型)。

请注意,这都是合乎逻辑、合理且站得住脚的。 typeof null === "object" 不是一个 bug,而是必须适应 Java 互操作性的二阶效应。

出现了许多不完美的向后合理化和/或约定,包括未定义表示隐式缺少值,null表示有意缺少值; 或者,undefined 是指不存在值,而 null 则是指不存在对象值。

与 Brendan Eich 的相关对话,截图供后代使用:

在此处输入图像描述

TLDR

undefined is a primitive value in JavaScript that indicates the implicit absence of a value. Uninitialized variables automatically have this value, and functions without an explicit return statement, return undefined.

null is also a primitive value in JavaScript. It indicates the intentional absence of an object value. null in JavaScript was designed to enable interoperability with Java.

typeof null returns "object" because of a peculiarity in the design of the language, stemming from the demand that JavaScript be interoperable with Java. It does not mean null is an instance of an object. It means: given the tree of primitive types in JavaScript, null is part of the "object-type primitive" subtree. This is explained more fully below.

Details

undefined is a primitive value that represents the implicit absence of a value. Note that undefined was not directly accessible until JavaScript 1.3 in 1998. This tells us that null was intended to be the value used by programmers when explicitly indicating the absence of a value. Uninitialized variables automatically have the value undefined. undefined is a one-of-a-kind type in the ECMAScript specification.

null is a primitive value that represents the intentional absence of an object value. null is also a one-of-a-kind type in the ECMAScript specification.

null in JavaScript was designed with a view to enable interoperability with Java, both from a "look" perspective, and from a programmatic perspective (eg the LiveConnect Java/JS bridge planned for 1996). Both Brendan Eich and others have since expressed distaste at the inclusion of two "absence of value" values, but in 1995 Eich was under orders to "make [JavaScript] look like Java".

Brendan Eich:

If I didn't have "Make it look like Java" as an order from management,
and I had more time (hard to unconfound these two causal factors), then I would have preferred a Self-like "everything's an object"
approach: no Boolean, Number, String wrappers. No undefined and null.
Sigh.

In order to accommodate Java's concept of null which, due to the strongly-typed nature of Java, can only be assigned to variables typed to a reference type (rather primitives), Eich chose to position the special null value at the top of the object prototype chain (i.e. the top of the reference types), and to include the null type as part of the set of "object-type primitives".

The typeof operator was added shortly thereafter in JavaScript 1.1, released on 19th August 1996.

From the V8 blog:

typeof null returns object, and not null, despite null being a
type of its own. To understand why, consider that the set of all
JavaScript types is divided into two groups:

  1. objects (i.e. the Object type)
  2. primitives (i.e. any non-object value)

As such, null means “no object value”, whereas undefined means “no
value”.

enter image description here

Following this line of thought, Brendan Eich designed JavaScript to
make typeof return 'object' for all values on the right-hand side,
i.e. all objects and null values, in the spirit of Java. That’s why
typeof null === 'object' despite the spec having a separate null type.

enter image description here

So Eich designed the hierarchy of primitive types to enable interoperability with Java. This led to him positioning null along with the "object-type primitives" on the hierarchy. To reflect this, when typeof was added to the language shortly thereafter, he chose typeof null to return "object".

The surprise expressed by JavaScript developers at typeof null === "object" is the result of an impedance mismatch (or abstraction leak) between a weakly-typed language (JavaScript) that has both null and undefined, and another, strongly-typed language (Java) that only has null, and in which null is strictly defined to refer to a reference type (not a primitive type).

Note that this is all logical, reasonable and defensible. typeof null === "object" is not a bug, but a second-order effect of having to accommodate Java interoperability.

A number of imperfect backwards rationalisations and/or conventions have emerged, including that undefined indicates implicit absence of a value, and that null indicates intentional absence of a value; or that undefined is the absence of a value, and null is specifically the absence of an object value.

A relevant conversation with Brendan Eich, screenshotted for posterity:

enter image description here

夏至、离别 2024-07-25 08:43:19
typeof null;      // object
typeof undefined; // undefined

值 null 表示有意不存在任何对象值。 它是 JavaScript 的原始值之一,对于布尔运算被视为 false。

var x = null;
var y;

x 被声明 & 定义为 null

y 已声明但未定义。 它被声明为没有值,因此它是未定义的。

z 未声明,因此如果您尝试使用 z 也将是未定义的。

typeof null;      // object
typeof undefined; // undefined

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

var x = null;
var y;

x is declared & defined as null

y is declared but not defined. It is declared with no value so it is undefined.

z is not declared so would also be undefined if you attempted to use z.

阿楠 2024-07-25 08:43:19

理解 null 和 undefined 的一种方法是了解它们出现的位置。

在以下情况下期望返回 null 值:

  • 查询 DOM 的方法

    console.log(window.document.getElementById("nonExistentElement")); 
      //打印:空 
      
  • 从 Ajax 请求接收的 JSON 响应


    {
      name: "Bob",
      address: null
    }
  • RegEx.exec

  • 处于不断变化状态的新功能。 以下返回 null:


        var proto = Object.getPrototypeOf(Object.getPrototypeOf({}));

       // But this returns undefined:

        Object.getOwnPropertyDescriptor({}, "a");

所有其他不存在的情况均由 undefined 表示(如@Axel 所示)。 以下每个打印“未定义”:

    var uninitalised;
    console.log(uninitalised);

    var obj = {};
    console.log(obj.nonExistent);

    function missingParam(missing){
        console.log(missing);
    }

    missingParam();

    var arr = [];
    console.log(arr.pop());        

当然,如果您决定编写 var unialized = null; 或者自己从方法中返回 null,那么在其他情况下就会出现 null。 但这应该是很明显的。

第三种情况是当您想要访问一个变量但您甚至不知道它是否已被声明时。 对于这种情况,请使用 typeof 来避免引用错误:

if(typeof unknown !== "undefined"){
    //use unknown
}

总之,当您操作 DOM、处理 Ajax 或使用某些 ECMAScript 5 功能时,请检查 null。 对于所有其他情况,可以安全地检查未定义的严格相等性:

if(value === undefined){
  // stuff
}

One way to make sense of null and undefined is to understand where each occurs.

Expect a null return value in the following situations:

  • Methods that query the DOM

    console.log(window.document.getElementById("nonExistentElement"));
    //Prints: null
    
  • JSON responses received from an Ajax request


    {
      name: "Bob",
      address: null
    }
  • RegEx.exec.

  • New functionality that is in a state of flux. The following returns null:


        var proto = Object.getPrototypeOf(Object.getPrototypeOf({}));

       // But this returns undefined:

        Object.getOwnPropertyDescriptor({}, "a");

All other cases of non-existence are denoted by undefined (as noted by @Axel). Each of the following prints "undefined":

    var uninitalised;
    console.log(uninitalised);

    var obj = {};
    console.log(obj.nonExistent);

    function missingParam(missing){
        console.log(missing);
    }

    missingParam();

    var arr = [];
    console.log(arr.pop());        

Of course if you decide to write var unitialised = null; or return null from a method yourself then you have null occurring in other situations. But that should be pretty obvious.

A third case is when you want to access a variable but you don't even know if it has been declared. For that case use typeof to avoid a reference error:

if(typeof unknown !== "undefined"){
    //use unknown
}

In summary check for null when you are manipulating the DOM, dealing with Ajax, or using certain ECMAScript 5 features. For all other cases it is safe to check for undefined with strict equality:

if(value === undefined){
  // stuff
}
仄言 2024-07-25 08:43:19

JavaScript 中许多不同空检查的比较:

http://jsfiddle.net/aaronhoffman/DdRHB/5/< /a>

// Variables to test
var myNull = null;
var myObject = {};
var myStringEmpty = "";
var myStringWhiteSpace = " ";
var myStringHello = "hello";
var myIntZero = 0;
var myIntOne = 1;
var myBoolTrue = true;
var myBoolFalse = false;
var myUndefined;

...trim...

http://aaron-hoffman. blogspot.com/2013/04/javascript-null-checking-undefined-and.html

Comparison of many different null checks in JavaScript:

http://jsfiddle.net/aaronhoffman/DdRHB/5/

// Variables to test
var myNull = null;
var myObject = {};
var myStringEmpty = "";
var myStringWhiteSpace = " ";
var myStringHello = "hello";
var myIntZero = 0;
var myIntOne = 1;
var myBoolTrue = true;
var myBoolFalse = false;
var myUndefined;

...trim...

http://aaron-hoffman.blogspot.com/2013/04/javascript-null-checking-undefined-and.html

JavaScript Null Check Comparison Chart

顾挽 2024-07-25 08:43:19

添加到 undefinednull 之间的区别是什么 的答案,来自 JavaScript 权威指南第 6 版,本页第 41 页

您可能会认为未定义代表系统级的、意外的、
或类似错误的值缺失和 null 来表示程序级别,
正常的或预期的价值缺失。 如果您需要分配其中之一
将这些值传递给变量或属性,或者将这些值之一传递给
一个函数,null 几乎总是正确的选择。

To add to the answer of What is the differrence between undefined and null, from JavaScript Definitive Guide 6th Edition, p.41 on this page:

You might consider undefined to represent system-level, unexpected,
or error-like absense of value and null to represent program-level,
normal, or expected absence of value. If you need to assign one of
these values to a variable or property or pass one of these values to
a function, null is almost always the right choice.

天煞孤星 2024-07-25 08:43:19

一些精度:

null 和未定义是两个不同的值。 一种表示名称不存在值,另一种表示名称不存在。


对于 if( o )if 中发生的情况如下:

计算括号 o 中的表达式,然后开始执行 if对括号中表达式的值进行类型强制 - 在我们的例子中为 o

JavaScript 中的 Falsy(将被强制为 false)值为:''、null、undefined、0 和 false

Some precisions:

null and undefined are two different values. One is representing the absence of a value for a name and the other is representing the absence of a name.


What happens in an if goes as follows for if( o ):

The expression in the parentheses o is evaluated, and then the if kicks in type-coercing the value of the expression in the parentheses - in our case o.

Falsy (that will get coerced to false) values in JavaScript are: '', null, undefined, 0, and false.

痴骨ら 2024-07-25 08:43:19

对于值相等(null==undefined),null 和 undefined 都是 false:它们都折叠为布尔值 false。 它们不是同一个对象(null!==未定义)。

undefined 是全局对象(浏览器中的“窗口”)的属性,但它是原始类型而不是对象本身。 它是未初始化的变量和没有 return 语句结尾的函数的默认值。

null 是对象的一个​​实例。 null 用于返回集合对象的 DOM 方法来指示空结果,这提供了 false 值而不指示错误。

null and undefined are both false for value equality (null==undefined): they both collapse to boolean false. They are not the same object (null!==undefined).

undefined is a property of the global object ("window" in browsers), but is a primitive type and not an object itself. It's the default value for uninitialized variables and functions ending without a return statement.

null is an instance of Object. null is used for DOM methods that return collection objects to indicate an empty result, which provides a false value without indicating an error.

撩人痒 2024-07-25 08:43:19

以下函数显示了原因并能够计算出差异:

function test() {
        var myObj = {};
        console.log(myObj.myProperty);
        myObj.myProperty = null;
        console.log(myObj.myProperty);
}

如果您调用,

test();

您会得到

未定义

第一个 console.log(...) 尝试从 myObj 获取 myProperty,而它尚未定义 - 所以它会返回“不明确的”。 将 null 分配给它后,第二个 console.log(...) 显然返回“null”,因为 myProperty 存在,但它的值为 null code> 分配给它。

为了能够查询这种差异,JavaScript 有 nullundefined:虽然 null 是 - 就像其他语言中的对象一样,< code>undefined 不能是对象,因为没有可用的实例(甚至不是 null 实例)。

The following function shows why and is capable for working out the difference:

function test() {
        var myObj = {};
        console.log(myObj.myProperty);
        myObj.myProperty = null;
        console.log(myObj.myProperty);
}

If you call

test();

You're getting

undefined

null

The first console.log(...) tries to get myProperty from myObj while it is not yet defined - so it gets back "undefined". After assigning null to it, the second console.log(...) returns obviously "null" because myProperty exists, but it has the value null assigned to it.

In order to be able to query this difference, JavaScript has null and undefined: While null is - just like in other languages an object, undefined cannot be an object because there is no instance (even not a null instance) available.

烟柳画桥 2024-07-25 08:43:19

例如,window.someWeirdProperty 未定义,因此

"window.someWeirdProperty === null" 计算结果为 false,而

"window.someWeirdProperty === undefined" code> 计算结果为 true。

此外,检查 if (!o) 与检查 if (o == null) 是否 ofalse 不同代码>.

For example window.someWeirdProperty is undefined, so

"window.someWeirdProperty === null" evaluates to false while

"window.someWeirdProperty === undefined" evaluates to true.

Moreover checkif if (!o) is not the same as checking if (o == null) for o being false.

如何视而不见 2024-07-25 08:43:19

摘自 Nicholas C. Zakas 的《面向对象 Javascript 原理》

但是当类型为 null 时为什么是对象呢? (事实上​​,这已被设计和维护 JavaScript 的委员会 TC39 承认为错误。您可以推断 null 是一个空对象指针,使“object”成为逻辑返回值,但这仍然令人困惑。)

Zakas,尼古拉斯·C. (2014-02-07)。 面向对象 JavaScript 的原理(Kindle 位置 226-227)。 无淀粉压榨机。 Kindle版。

也就是说:

var game = null; //typeof(game) is "object"

game.score = 100;//null is not an object, what the heck!?
game instanceof Object; //false, so it's not an instance but it's type is object
//let's make this primitive variable an object;
game = {}; 
typeof(game);//it is an object
game instanceof Object; //true, yay!!!
game.score = 100;

未定义的情况:

var score; //at this point 'score' is undefined
typeof(score); //'undefined'
var score.player = "felix"; //'undefined' is not an object
score instanceof Object; //false, oh I already knew that.

From "The Principles of Object-Oriented Javascript" by Nicholas C. Zakas

But why an object when the type is null? (In fact, this has been acknowledged as an error by TC39, the committee that designs and maintains JavaScript. You could reason that null is an empty object pointer, making "object" a logical return value, but that’s still confusing.)

Zakas, Nicholas C. (2014-02-07). The Principles of Object-Oriented JavaScript (Kindle Locations 226-227). No Starch Press. Kindle Edition.

That said:

var game = null; //typeof(game) is "object"

game.score = 100;//null is not an object, what the heck!?
game instanceof Object; //false, so it's not an instance but it's type is object
//let's make this primitive variable an object;
game = {}; 
typeof(game);//it is an object
game instanceof Object; //true, yay!!!
game.score = 100;

Undefined case:

var score; //at this point 'score' is undefined
typeof(score); //'undefined'
var score.player = "felix"; //'undefined' is not an object
score instanceof Object; //false, oh I already knew that.
蛮可爱 2024-07-25 08:43:19

思考“null”的最佳方法是回忆一下类似概念在数据库中的使用方式,它表示某个字段“根本不包含任何值”。

  • 是的,该物品的价值已知; 它“已定义”。 它已经被初始化。
  • 该项目的值是:“没有值。”

对于编写更容易调试的程序来说,这是一种非常有用的技术。 一个“未定义”的变量可能是错误的结果......(你怎么知道?)......但是如果该变量包含值“null”,你就知道“某人,某处在这个程序中,将其设置为“null”。”因此,我建议,当您需要删除变量的值时,不要“删除”...将其设置为'无效的。' 旧值将被孤立,很快就会被垃圾收集; 新值是“(现在)没有价值”。 在这两种情况下,变量的状态都是确定的:“显然,它是故意的。”

The best way to think about 'null' is to recall how the similar concept is used in databases, where it indicates that a field contains "no value at all."

  • Yes, the item's value is known; it is 'defined.' It has been initialized.
  • The item's value is: "there is no value."

This is a very useful technique for writing programs that are more-easily debugged. An 'undefined' variable might be the result of a bug ... (how would you know?) ... but if the variable contains the value 'null,' you know that "someone, somewhere in this program, set it to 'null.'" Therefore, I suggest that, when you need to get rid of the value of a variable, don't "delete" ... set it to 'null.' The old value will be orphaned and soon will be garbage-collected; the new value is, "there is no value (now)." In both cases, the variable's state is certain: "it obviously, deliberately, got that way."

征棹 2024-07-25 08:43:19

Javascript 中,null 不是 object 类型,它是 primitave 类型。

有什么区别?
未定义指的是尚未设置的指针。
Null 指的是空指针,例如有人手动将变量设置为 null 类型

In Javascript null is not an object type it is a primitave type.

What is the difference?
Undefined refers to a pointer that has not been set.
Null refers to the null pointer for example something has manually set a variable to be of type null

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文