JavaScript 中 null 和 undefined 有什么区别?

发布于 2024-10-18 16:29:31 字数 69 浏览 2 评论 0原文

JavaScript 中 nullundefined 有什么区别?

What is the difference between null and undefined in JavaScript?

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

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

发布评论

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

评论(30

过去的过去 2024-10-25 16:29:31

undefined 表示变量已被声明但尚未赋值:

var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined

null 是一个赋值值。它可以被分配给一个变量作为无值的表示:

var testVar = null;
console.log(testVar); //shows null
console.log(typeof testVar); //shows object

从前面的示例中可以清楚地看出,undefinednull 是两种不同的类型:undefined 本身就是一个类型(未定义),而 null 是一个对象。

证明 :

console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)

null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'

undefined means a variable has been declared but has not yet been assigned a value :

var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined

null is an assignment value. It can be assigned to a variable as a representation of no value :

var testVar = null;
console.log(testVar); //shows null
console.log(typeof testVar); //shows object

From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Proof :

console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)

and

null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'
半衬遮猫 2024-10-25 16:29:31

这种差异可以用卫生纸支架来解释:

  • 非零值就像一个带有卫生纸卷的支架,并且管子上仍然有纸巾。

  • 零值就像一个带有空卫生纸管的支架。

  • 空值就像一个甚至没有纸巾管的支架。

  • 未定义的值类似于持有人本身丢失。

< /a>

The difference can be explained with toilet tissue holder:

  • A non-zero value is like a holder with roll of toilet tissue and there's tissue still on the tube.

  • A zero value is like a holder with an empty toilet tissue tube.

  • A null value is like a holder that doesn't even have a tissue tube.

  • An undefined value is similar to the holder itself being missing.

公布 2024-10-25 16:29:31

我从这里选择了这个

未定义值是当变量没有定义时使用的原始值。
已被赋值。

null 值是一个原始值,表示 null、empty、
或不存在的参考。

当您通过 var 声明变量并且不给它赋值时,它将具有未定义的值。就其本身而言,如果您尝试 WScript.Echo() 或alert() 这个值,您将看不到任何内容。但是,如果您向其附加一个空白字符串,那么它会突然出现:

var s;
WScript.Echo(s);
WScript.Echo("" + s);

您可以声明一个变量,将其设置为 null,并且行为是相同的,只是您会看到打印出“null”与“undefined”。这确实是一个很小的差异。

您甚至可以将未定义的变量与 null 进行比较,反之亦然,条件将为 true:

undefined == null
null == undefined

但是,它们被视为两种不同的类型。虽然 undefined 本身就是一个类型,但 null 被认为是一个特殊的对象值。您可以通过使用 typeof() 来查看这一点,它返回一个表示变量一般类型的字符串:

var a;
WScript.Echo(typeof(a));
var b = null;
WScript.Echo(typeof(b));

运行上述脚本将产生以下输出:

undefined
object

无论它们的类型不同,如果您尝试访问它们,它们的行为仍然相同任一成员,例如,这就是说他们将抛出异常。使用 WSH,您将看到可怕的“'varname' 为 null 或不是对象”,如果您幸运的话(但这是另一篇文章的主题)。

您可以显式地将变量设置为未定义,但我强烈建议不要这样做。我建议仅将变量设置为 null,并将您忘记设置的值保留为未定义。同时,我真的鼓励您始终设置每个变量。 JavaScript 的作用域链与 C 风格语言不同,即使是资深程序员也很容易感到困惑,而将变量设置为 null 是防止基于它的错误的最佳方法。

您将看到未定义弹出的另一个实例是使用删除运算符时。我们这些来自 C 世界的人可能会错误地将其解释为破坏一个物体,但事实并非如此。此操作的作用是从数组中删除下标或从对象中删除成员。对于数组,它不会影响长度,但下标现在被认为是未定义的。

var a = [ 'a', 'b', 'c' ];
delete a[1];
for (var i = 0; i < a.length; i++)
WScript.Echo((i+".) "+a[i]);

上面脚本的结果是:

0.) a
1.) undefined
2.) c

当读取一个不存在的下标或成员时,你也会得到 undefined 返回。

null 和 undefined 之间的区别是:JavaScript 永远不会将任何内容设置为 null,这通常是我们所做的。虽然我们可以将变量设置为 undefined,但我们更喜欢 null,因为这不是为我们做过的事情。当您调试时,这意味着任何设置为 null 的内容都是您自己完成的,而不是 JavaScript。除此之外,这两个特殊值几乎相等。

I picked this from here

The undefined value is a primitive value used when a variable has not
been assigned a value.

The null value is a primitive value that represents the null, empty,
or non-existent reference.

When you declare a variable through var and do not give it a value, it will have the value undefined. By itself, if you try to WScript.Echo() or alert() this value, you won't see anything. However, if you append a blank string to it then suddenly it'll appear:

var s;
WScript.Echo(s);
WScript.Echo("" + s);

You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". This is a small difference indeed.

You can even compare a variable that is undefined to null or vice versa, and the condition will be true:

undefined == null
null == undefined

They are, however, considered to be two different types. While undefined is a type all to itself, null is considered to be a special object value. You can see this by using typeof() which returns a string representing the general type of a variable:

var a;
WScript.Echo(typeof(a));
var b = null;
WScript.Echo(typeof(b));

Running the above script will result in the following output:

undefined
object

Regardless of their being different types, they will still act the same if you try to access a member of either one, e.g. that is to say they will throw an exception. With WSH you will see the dreaded "'varname' is null or not an object" and that's if you're lucky (but that's a topic for another article).

You can explicitely set a variable to be undefined, but I highly advise against it. I recommend only setting variables to null and leave undefined the value for things you forgot to set. At the same time, I really encourage you to always set every variable. JavaScript has a scope chain different than that of C-style languages, easily confusing even veteran programmers, and setting variables to null is the best way to prevent bugs based on it.

Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.

var a = [ 'a', 'b', 'c' ];
delete a[1];
for (var i = 0; i < a.length; i++)
WScript.Echo((i+".) "+a[i]);

The result of the above script is:

0.) a
1.) undefined
2.) c

You will also get undefined returned when reading a subscript or member that never existed.

The difference between null and undefined is: JavaScript will never set anything to null, that's usually what we do. While we can set variables to undefined, we prefer null because it's not something that is ever done for us. When you're debugging this means that anything set to null is of your own doing and not JavaScript. Beyond that, these two special values are nearly equivalent.

清醇 2024-10-25 16:29:31

请仔细阅读以下内容。它应该消除您对 JavaScript 中 nullundefined 之间差异的所有疑虑。此外,您可以使用本答案末尾的实用函数来获取更具体类型的变量。

在 JavaScript 中,我们可以有以下类型的变量:

  1. 未声明的变量
  2. 已声明但未分配的变量
  3. 使用文字 undefined 分配
  4. 的变量 使用文字 null
  5. 分配的变量 使用 以外的任何内容分配的变量undefinednull

下面一一解释这些情况:

  1. 未声明的变量

    • 只能使用返回字符串'undefined'typeof运算符进行检查
    • 无法使用松散相等运算符 ( == undefined ) 进行检查,更不用说严格相等运算符 ( === undefined ),
      以及 if 语句三元运算符 ( ? : ) - 这些会抛出引用错误
  2. 已声明但未分配的变量< /strong>


    • typeof 返回字符串'undefined'
    • == 检查 null 返回 true
    • == 检查 undefined 返回 true
    • === 检查 null 返回 false
    • === 检查 undefined 返回 true
    • if 语句三元运算符是否为假值 ( ? : )
  3. 用文字 undefined 赋值的变量
    这些变量的处理方式与已声明但未分配的变量完全相同。

  4. 用文字指定的变量 null

    • typeof 返回字符串'object'
    • == 检查 null 返回 true
    • == 检查 undefined 返回 true
    • === 检查 null 返回 true
    • === 检查 undefined 返回 false
    • if 语句三元运算符是否为假值 ( ? : )
  5. 分配除 undefinednull

    之外的变量

    • typeof 返回以下字符串之一:'bigint''boolean''function''number' , '对象', '字符串', '符号'

下面提供了对变量进行正确类型检查的算法:

  1. 获取我们变量的typeof,如果不是'则返回它object'
  2. 检查 null,因为 typeof null 返回 'object' 以及
  3. 评估 Object.prototype.toString。 call(o) 使用 switch 语句返回更精确的值。 ObjecttoString 方法返回类似于本机/主机对象的 '[object ConstructorName]' 的字符串。对于所有其他对象(用户定义的对象),它始终返回 '[object Object]'
  4. 如果最后一部分是这种情况(变量的字符串化版本为 '[object Object] ')并且参数 returnConstructorBooleantrue,它将尝试通过 toString 获取构造函数的名称,并且从那里提取名称。如果无法访问构造函数,则照常返回'object'。如果字符串不包含其名称,则返回 'anonymous'

(支持 ECMAScript 2020 之前的所有类型)

function TypeOf(o, returnConstructorBoolean) {
  const type = typeof o

  if (type !== 'object') return type
  if (o === null)        return 'null'

  const toString = Object.prototype.toString.call(o)

  switch (toString) {
    // Value types: 6
    case '[object BigInt]':            return 'bigint'
    case '[object Boolean]':           return 'boolean'
    case '[object Date]':              return 'date'
    case '[object Number]':            return 'number'
    case '[object String]':            return 'string'
    case '[object Symbol]':            return 'symbol'

    // Error types: 7
    case '[object Error]':             return 'error'
    case '[object EvalError]':         return 'evalerror'
    case '[object RangeError]':        return 'rangeerror'
    case '[object ReferenceError]':    return 'referenceerror'
    case '[object SyntaxError]':       return 'syntaxerror'
    case '[object TypeError]':         return 'typeerror'
    case '[object URIError]':          return 'urierror'

    // Indexed Collection and Helper types: 13
    case '[object Array]':             return 'array'
    case '[object Int8Array]':         return 'int8array'
    case '[object Uint8Array]':        return 'uint8array'
    case '[object Uint8ClampedArray]': return 'uint8clampedarray'
    case '[object Int16Array]':        return 'int16array'
    case '[object Uint16Array]':       return 'uint16array'
    case '[object Int32Array]':        return 'int32array'
    case '[object Uint32Array]':       return 'uint32array'
    case '[object Float32Array]':      return 'float32array'
    case '[object Float64Array]':      return 'float64array'
    case '[object ArrayBuffer]':       return 'arraybuffer'
    case '[object SharedArrayBuffer]': return 'sharedarraybuffer'
    case '[object DataView]':          return 'dataview'

    // Keyed Collection types: 2
    case '[object Map]':               return 'map'
    case '[object WeakMap]':           return 'weakmap'

    // Set types: 2
    case '[object Set]':               return 'set'
    case '[object WeakSet]':           return 'weakset'

    // Operation types: 3
    case '[object RegExp]':            return 'regexp'
    case '[object Proxy]':             return 'proxy'
    case '[object Promise]':           return 'promise'

    // Plain objects
    case '[object Object]':
      if (!returnConstructorBoolean)
        return type

      const _prototype = Object.getPrototypeOf(o)
      if (!_prototype)              
        return type

      const _constructor = _prototype.constructor
      if (!_constructor)            
        return type

      const matches = Function.prototype.toString.call(_constructor).match(/^function\s*([^\s(]+)/)
        return matches ? matches[1] : 'anonymous'

    default: return toString.split(' ')[1].slice(0, -1)
  }
}

Please read the following carefully. It should remove all your doubts regarding the difference between null and undefined in JavaScript. Also, you can use the utility function at the end of this answer to get more specific types of variables.

In JavaScript we can have the following types of variables:

  1. Undeclared Variables
  2. Declared but Unassigned Variables
  3. Variables assigned with literal undefined
  4. Variables assigned with literal null
  5. Variables assigned with anything other than undefined or null

The following explains each of these cases one by one:

  1. Undeclared Variables

    • Can only be checked with the typeof operator which returns string 'undefined'
    • Cannot be checked with the loose equality operator ( == undefined ), let alone the strict equality operator ( === undefined ),
      as well as if-statements and ternary operators ( ? : ) — these throw Reference Errors
  2. Declared but Unassigned Variables

    • typeof returns string 'undefined'
    • == check with null returns true
    • == check with undefined returns true
    • === check with null returns false
    • === check with undefined returns true
    • Is falsy to if-statements and ternary operators ( ? : )
  3. Variables assigned with literal undefined
    These variables are treated exactly the same as Declared But Unassigned Variables.

  4. Variables assigned with literal null

    • typeof returns string 'object'
    • == check with null returns true
    • == check with undefined returns true
    • === check with null returns true
    • === check with undefined returns false
    • Is falsy to if-statements and ternary operators ( ? : )
  5. Variables assigned with anything other than undefined or null

    • typeof returns one of the following strings: 'bigint', 'boolean', 'function', 'number', 'object', 'string', 'symbol'

Following provides the algorithm for correct type checking of a variable:

  1. Get the typeof our variable and return it if it isn't 'object'
  2. Check for null, as typeof null returns 'object' as well
  3. Evaluate Object.prototype.toString.call(o) with a switch statement to return a more precise value. Object's toString method returns strings that look like '[object ConstructorName]' for native/host objects. For all other objects (user-defined objects), it always returns '[object Object]'
  4. If that last part is the case (the stringified version of the variable being '[object Object]') and the parameter returnConstructorBoolean is true, it will try to get the name of the constructor by toString-ing it and extracting the name from there. If the constructor can't be reached, 'object' is returned as usual. If the string doesn't contain its name, 'anonymous' is returned

(supports all types up to ECMAScript 2020)

function TypeOf(o, returnConstructorBoolean) {
  const type = typeof o

  if (type !== 'object') return type
  if (o === null)        return 'null'

  const toString = Object.prototype.toString.call(o)

  switch (toString) {
    // Value types: 6
    case '[object BigInt]':            return 'bigint'
    case '[object Boolean]':           return 'boolean'
    case '[object Date]':              return 'date'
    case '[object Number]':            return 'number'
    case '[object String]':            return 'string'
    case '[object Symbol]':            return 'symbol'

    // Error types: 7
    case '[object Error]':             return 'error'
    case '[object EvalError]':         return 'evalerror'
    case '[object RangeError]':        return 'rangeerror'
    case '[object ReferenceError]':    return 'referenceerror'
    case '[object SyntaxError]':       return 'syntaxerror'
    case '[object TypeError]':         return 'typeerror'
    case '[object URIError]':          return 'urierror'

    // Indexed Collection and Helper types: 13
    case '[object Array]':             return 'array'
    case '[object Int8Array]':         return 'int8array'
    case '[object Uint8Array]':        return 'uint8array'
    case '[object Uint8ClampedArray]': return 'uint8clampedarray'
    case '[object Int16Array]':        return 'int16array'
    case '[object Uint16Array]':       return 'uint16array'
    case '[object Int32Array]':        return 'int32array'
    case '[object Uint32Array]':       return 'uint32array'
    case '[object Float32Array]':      return 'float32array'
    case '[object Float64Array]':      return 'float64array'
    case '[object ArrayBuffer]':       return 'arraybuffer'
    case '[object SharedArrayBuffer]': return 'sharedarraybuffer'
    case '[object DataView]':          return 'dataview'

    // Keyed Collection types: 2
    case '[object Map]':               return 'map'
    case '[object WeakMap]':           return 'weakmap'

    // Set types: 2
    case '[object Set]':               return 'set'
    case '[object WeakSet]':           return 'weakset'

    // Operation types: 3
    case '[object RegExp]':            return 'regexp'
    case '[object Proxy]':             return 'proxy'
    case '[object Promise]':           return 'promise'

    // Plain objects
    case '[object Object]':
      if (!returnConstructorBoolean)
        return type

      const _prototype = Object.getPrototypeOf(o)
      if (!_prototype)              
        return type

      const _constructor = _prototype.constructor
      if (!_constructor)            
        return type

      const matches = Function.prototype.toString.call(_constructor).match(/^function\s*([^\s(]+)/)
        return matches ? matches[1] : 'anonymous'

    default: return toString.split(' ')[1].slice(0, -1)
  }
}
绮烟 2024-10-25 16:29:31

null 是一个特殊关键字,表示缺少值。

将其视为一个值,例如:

  • “foo”是字符串,
  • true 是布尔值,
  • 1234 是数字,
  • null 是未定义的。

undefined属性表示变量还没有被赋值,包括null。
就像

var foo;

定义的空变量是数据类型未定义null


一样,它们都表示没有值的变量的值


null 不代表没有值的字符串 - 空字符串 -


Like

var a = ''; 
console.log(typeof a); // string 
console.log(a == null); //false 
console.log(a == undefined); // false 

现在如果

var a;
console.log(a == null); //true
console.log(a == undefined); //true 

BUT

var a; 
console.log(a === null); //false 
console.log(a === undefined); // true

SO 每个人都有自己的使用方式

undefined 使用它来比较变量数据类型

null 使用它来清空变量的值

var a = 'javascript';
a = null ; // will change the type of variable "a" from string to object 

null is a special keyword that indicates an absence of value.

think about it as a value, like:

  • "foo" is string,
  • true is boolean ,
  • 1234 is number,
  • null is undefined.

undefined property indicates that a variable has not been assigned a value including null too .
Like

var foo;

defined empty variable is null of datatype undefined


Both of them are representing a value of a variable with no value

AND
null doesn't represent a string that has no value - empty string-


Like

var a = ''; 
console.log(typeof a); // string 
console.log(a == null); //false 
console.log(a == undefined); // false 

Now if

var a;
console.log(a == null); //true
console.log(a == undefined); //true 

BUT

var a; 
console.log(a === null); //false 
console.log(a === undefined); // true

SO each one has it own way to use

undefined use it to compare the variable data type

null use it to empty a value of a variable

var a = 'javascript';
a = null ; // will change the type of variable "a" from string to object 
一瞬间的火花 2024-10-25 16:29:31

null:变量没有值; 未定义:变量本身不存在;

..其中变量是与值关联的符号名称。

JS 可以很好地使用 null 隐式初始化新声明的变量,但事实并非如此。

null: absence of value for a variable; undefined: absence of variable itself;

..where variable is a symbolic name associated with a value.

JS could be kind enough to implicitly init newly declared variables with null, but it does not.

长伴 2024-10-25 16:29:31

已经给出了很多“技术”答案,从 JS 作为一种编程语言的有限角度来看,它们大多都是正确的。

但是,我想添加以下想法,特别是当您将 TypeScript 代码作为更大的项目/(企业)应用程序的一部分编写时:

  • 与某种后端交谈时,您很可能会收到 JSON,
  • 而某些后端正确避免在 JSON 中使用“null”(删除这些属性),其他人则不会
  • 现在,而“null”可能意味着故意丢失该值,但更多时候它并不传达这种含义。大多数数据库使用“null”只是因为它们没有“未定义”类型。但其含义实际上只是“未定义”。
  • 因此,您永远无法知道“null”值是否真的意味着故意缺席。因此,“空”并不能真正意味着故意选择“缺失值”。一般情况下是无法判定的。
  • 因此,语义上,“null”和“未定义”实际上是完全相同的。

因此,为了协调事情,我严格反对使用“null”,并希望鼓励您停止在代码中使用“null”。这比您想象的要容易得多。别误会我的意思。我并不是说不处理“空”值,只是为了避免在代码中显式使用它们。换句话说:您的代码仍然应该能够处理来自应用程序外部的意外传递的“空”值,例如通过像 Angular,或第 3 方后端。

以下是使其成为可能的准则:

  • 避免直接未定义类型保护(例如if (value === undefined) { ... }
  • 相反,使用间接类型保护(又名真实性检查)例如 if (value) { ... }
    • 只要 0 或空字符串有意义,就使用
      • 显式辅助方法,例如 Lodash 的 isNil
      • 或在比较中包含有意义的值(例如 if (!value && value !== 0) { ... })
  • 考虑使用 lint 规则 禁止使用 null

A lot of "technical" answers have been given, all of them mostly correct from the limited point of view of JS as a mere programming language.

However, I would like to add the following thoughts, especially when you're writing TypeScript code as part of a bigger project / (enterprise) application:

  • When talking with a Backend of some kind you'll most probably receive JSON
  • While some backends correctly avoid the use of "null" in their JSON (removing those properties), others do not
  • Now, while "null" may mean that the value is missing deliberately, more often it does not convey this meaning. Most databases use "null" just because they don't have an "undefined" type. But the meaning really just is "undefined".
  • Because of that, you can never know if a "null" value really means deliberate absence. Therefore "null" cannot really mean the deliberate choice of "missing value". It is undecidable in general.
  • As a consequence, semantically, "null" and "undefined" are exactly the same thing in practice.

Therefore, in an effort to harmonize things I'm strictly against using "null" and want to encourage you to stop using "null" in your code. It's far easier than you might think. Don't get me wrong. I'm not talking about not handling "null" values, only to avoid explicitly using them in your code. Put differently: your code should still be able to work with accidentally passed "null" values coming from outside your application, e.g. via a 3rd party lib like Angular, or a 3rd party backend.

Here are the guidelines that make it possible:

  • avoid direct undefined type guards (e.g. if (value === undefined) { ... }.
  • Instead, use indirect type guards (aka truthiness checks) e.g. if (value) { ... }
    • Whenever 0 or empty strings are meaningful, use either
      • an explicit helper method like Lodash's isNil
      • or include the meaningful value in the comparison (e.g. if (!value && value !== 0) { ... })
  • Consider using a lint rule that disallows the usage of null
长不大的小祸害 2024-10-25 16:29:31

您可能认为 undefined 代表系统级、意外或类似错误的值缺失,而 null 代表程序级​​、正常或预期的值缺失。

通过 JavaScript:权威指南

You might consider undefined to represent a system-level, unexpected, or error-like absence of value and null to represent program-level, normal, or expected absence of value.

via JavaScript:The Definitive Guide

高冷爸爸 2024-10-25 16:29:31

理解差异的最好方法是首先理清 JavaScript 的内部工作原理,并理解它们之间的含义差异:

let supervisor = "None"
    // I have a supervisor named "None"

let supervisor = null
    // I do NOT have a supervisor. It is a FACT that I do not.

let supervisor = undefined
    // I may or may not have a supervisor. I either don't know
    // if I do or not, or I am choosing not to tell you. It is
    // irrelevant or none of your business.

这三种情况之间存在含义差异,JavaScript 用两个不同的值来区分后两种情况、null未定义。您可以自由地明确使用这些值来传达这些含义。

那么由于这种哲学基础而产生的一些 JavaScript 特定问题是什么?

  1. 没有初始值设定项的声明变量的值是未定义,因为您从未说过任何有关预期值的信息。

    让主管;
    断言(主管===未定义);
    
  2. 从未设置过的对象属性的计算结果为未定义,因为没有人说过有关该属性的任何事情。

    const 狗 = { name: 'Sparky', 年龄: 2 };
    断言(狗.breed ===未定义);
    
  3. nullundefined 彼此“相似”,因为 Brendan Eich 是这么说的。但它们显然并不相等。

    assert(null == undefined);
    断言(空!==未定义);
    
  4. 幸运的是,

    nullundefined 具有不同的类型。 null 属于Null 类型,undefined 属于Undefine 类型。这是在规范中的,但你永远不会知道这一点,因为 typeof 很奇怪,我不会在这里重复。

  5. 在没有显式 return 语句的情况下到达其主体末尾的函数将返回 undefined,因为您对它返回

顺便说一句,JavaScript 中还有其他形式的“虚无”(学习哲学是件好事……)

  • NaN
  • 使用从未声明过的变量并收到 ReferenceError< /code>
  • 在其临时死区中使用 letconst 定义的局部变量并接收 ReferenceError
  • 稀疏数组中的空单元格。是的,尽管它们将 === 与未定义进行比较,但它们甚至都不是未定义

    <前><代码>$节点
    >常量 a = [1,未定义,2]
    >常量 b = [1, , 2]
    >一个
    [ 1,未定义,2 ]
    >乙
    [ 1, <1 个空项目>, 2 ]

The best way to understand the difference is to first clear your mind of the inner workings of JavaScript and just understand the differences in meaning between:

let supervisor = "None"
    // I have a supervisor named "None"

let supervisor = null
    // I do NOT have a supervisor. It is a FACT that I do not.

let supervisor = undefined
    // I may or may not have a supervisor. I either don't know
    // if I do or not, or I am choosing not to tell you. It is
    // irrelevant or none of your business.

There is a difference in meaning between these three cases, and JavaScript distinguishes the latter two cases with two different values, null and undefined. You are free to use those values explicitly to convey those meanings.

So what are some of the JavaScript-specific issues that arise due to this philosophical basis?

  1. A declared variable without an initializer gets the value undefined because you never said anything about the what the intended value was.

    let supervisor;
    assert(supervisor === undefined);
    
  2. A property of an object that has never been set evaluates to undefined because no one ever said anything about that property.

    const dog = { name: 'Sparky', age: 2 };
    assert(dog.breed === undefined);
    
  3. null and undefined are "similar" to each other because Brendan Eich said so. But they are emphatically not equal to each other.

    assert(null == undefined);
    assert(null !== undefined);
    
  4. null and undefined thankfully have different types. null belongs to the type Null and undefined to the type Undefined. This is in the spec, but you would never know this because of the typeof weirdness which I will not repeat here.

  5. A function reaching the end of its body without an explicit return statement returns undefined since you don't know anything about what it returned.

By the way, there are other forms of "nothingness" in JavaScript (it's good to have studied Philosophy....)

  • NaN
  • Using a variable that has never been declared and receiving a ReferenceError
  • Using a let or const defined local variable in its temporal dead zone and receiving a ReferenceError
  • Empty cells in sparse arrays. Yes these are not even undefined although they compare === to undefined.

    $ node
    > const a = [1, undefined, 2]
    > const b = [1, , 2]
    > a
    [ 1, undefined, 2 ]
    > b
    [ 1, <1 empty item>, 2 ]
    
要走就滚别墨迹 2024-10-25 16:29:31

null 是一个特殊值,意思是“无值”。 null 是一个特殊的对象,因为 typeof null 返回“object”。

另一方面,undefined 表示该变量尚未声明,或者尚未赋值。

null is a special value meaning "no value". null is a special object because typeof null returns 'object'.

On the other hand, undefined means that the variable has not been declared, or has not been given a value.

怼怹恏 2024-10-25 16:29:31

nullundefined 是两种不同的对象类型,它们具有以下共同点:

  • 两者都只能保存单个值,nullundefined分别;
  • 两者都没有属性或方法,尝试读取其中任何一个的任何属性都会导致运行时错误(对于所有其他对象,如果尝试读取不存在的属性,您将获得值未定义 );
  • ==!= 运算符认为 nullundefined 值彼此相等,且不等于任何其他值。

然而相似之处到此为止。这一次,关键字 nullundefined 的实现方式存在根本性差异。这并不明显,但请考虑以下示例:

var undefined = "foo";
WScript.Echo(undefined); // This will print: foo

undefinedNaNInfinity 只是预初始化的“超全局”变量的名称 - 它们已初始化在运行时,可以被具有相同名称的普通全局或局部变量覆盖。

现在,让我们对 null 尝试同样的操作:

var null = "foo"; // This will cause a compile-time error
WScript.Echo(null);

哎呀! nulltruefalse 是保留关键字 - 编译器不允许您将它们用作变量或属性名称

另一个区别是 undefined 是原始类型,而 null 是对象类型(表示不存在对象引用)。请考虑以下事项:

WScript.Echo(typeof false); // Will print: boolean
WScript.Echo(typeof 0); // Will print: number
WScript.Echo(typeof ""); // Will print: string
WScript.Echo(typeof {}); // Will print: object
WScript.Echo(typeof undefined); // Will print: undefined
WScript.Echo(typeof null); // (!!!) Will print: object

此外,在数字上下文中处理 nullundefined 的方式存在重要差异:

var a; // declared but uninitialized variables hold the value undefined
WScript.Echo(a === undefined); // Prints: -1

var b = null; // the value null must be explicitly assigned 
WScript.Echo(b === null); // Prints: -1

WScript.Echo(a == b); // Prints: -1 (as expected)
WScript.Echo(a >= b); // Prints: 0 (WTF!?)

WScript.Echo(a >= a); // Prints: 0 (!!!???)
WScript.Echo(isNaN(a)); // Prints: -1 (a evaluates to NaN!)
WScript.Echo(1*a); // Prints: -1.#IND (in Echo output this means NaN)

WScript.Echo(b >= b); // Prints: -1 (as expected)
WScript.Echo(isNaN(b)); // Prints: 0 (b evaluates to a valid number)
WScript.Echo(1*b); // Prints: 0 (b evaluates to 0)

WScript.Echo(a >= 0 && a <= 0); // Prints: 0 (as expected)
WScript.Echo(a == 0); // Prints: 0 (as expected)
WScript.Echo(b >= 0 && b <= 0); // Prints: -1 (as expected)
WScript.Echo(b == 0); // Prints: 0 (!!!)

null 变为 0 当用于算术表达式或数字比较时 - 与 false 类似,它基本上只是一种特殊的“零”。另一方面,未定义是真正的“无”,当您尝试在数字上下文中使用它时,它会变成NaN(“不是数字”)。

请注意,nullundefined 会受到 ==!= 运算符的特殊处理,但您可以测试 true ab 与表达式 (a >= b && a <= b) 的数值相等。

null and undefined are two distinct object types which have the following in common:

  • both can only hold a single value, null and undefined respectively;
  • both have no properties or methods and an attempt to read any properties of either will result in a run-time error (for all other objects, you get value undefined if you try to read a non-existent property);
  • values null and undefined are considered equal to each other and to nothing else by == and != operators.

The similarities however end here. For once, there is a fundamental difference in the way how keywords null and undefined are implemented. This is not obvious, but consider the following example:

var undefined = "foo";
WScript.Echo(undefined); // This will print: foo

undefined, NaN and Infinity are just names of preinitialized "superglobal" variables - they are initialized at run-time and can be overridden by normal global or local variable with the same names.

Now, let's try the same thing with null:

var null = "foo"; // This will cause a compile-time error
WScript.Echo(null);

Oops! null, true and false are reserved keywords - compiler won't let you use them as variable or property names

Another difference is that undefined is a primitive type, while null is an object type (indicating the absense of an object reference). Consider the following:

WScript.Echo(typeof false); // Will print: boolean
WScript.Echo(typeof 0); // Will print: number
WScript.Echo(typeof ""); // Will print: string
WScript.Echo(typeof {}); // Will print: object
WScript.Echo(typeof undefined); // Will print: undefined
WScript.Echo(typeof null); // (!!!) Will print: object

Also, there is an important difference in the way null and undefined are treated in numeric context:

var a; // declared but uninitialized variables hold the value undefined
WScript.Echo(a === undefined); // Prints: -1

var b = null; // the value null must be explicitly assigned 
WScript.Echo(b === null); // Prints: -1

WScript.Echo(a == b); // Prints: -1 (as expected)
WScript.Echo(a >= b); // Prints: 0 (WTF!?)

WScript.Echo(a >= a); // Prints: 0 (!!!???)
WScript.Echo(isNaN(a)); // Prints: -1 (a evaluates to NaN!)
WScript.Echo(1*a); // Prints: -1.#IND (in Echo output this means NaN)

WScript.Echo(b >= b); // Prints: -1 (as expected)
WScript.Echo(isNaN(b)); // Prints: 0 (b evaluates to a valid number)
WScript.Echo(1*b); // Prints: 0 (b evaluates to 0)

WScript.Echo(a >= 0 && a <= 0); // Prints: 0 (as expected)
WScript.Echo(a == 0); // Prints: 0 (as expected)
WScript.Echo(b >= 0 && b <= 0); // Prints: -1 (as expected)
WScript.Echo(b == 0); // Prints: 0 (!!!)

null becomes 0 when used in arithmetic expressions or numeric comparisons - similarly to false, it is basically just a special kind of "zero". undefined, on the other hand, is a true "nothing" and becomes NaN ("not a number") when you try to use it in numeric context.

Note that null and undefined receive a special treatment from == and != operators, but you can test true numeric equality of a and b with the expression (a >= b && a <= b).

我一直都在从未离去 2024-10-25 16:29:31

我将解释 undefinednullUncaught ReferenceError:

1 - Uncaught ReferenceError :变量 has not已在您的脚本中声明,但没有引用此变量
2 - 未定义:已声明变量但未初始化
3 - null :声明变量且为空值

I'll explain undefined, null and Uncaught ReferenceError:

1 - Uncaught ReferenceError : variable has not been declared in your script, there is no reference to this varaible
2 - undefined: Variable declared but does not initialised
3 - null : Variable declared and is an empty value

叫思念不要吵 2024-10-25 16:29:31

未定义意味着变量已被声明但没有值:

var var1;
alert(var1); //undefined
alert(typeof var1); //undefined

Null 是赋值:

var var2= null;
alert(var2); //null
alert(typeof var2); //object

Undefined means a variable has been declared but has no value:

var var1;
alert(var1); //undefined
alert(typeof var1); //undefined

Null is an assignment:

var var2= null;
alert(var2); //null
alert(typeof var2); //object
梦行七里 2024-10-25 16:29:31

tl;dr

使用 null 设置一个您知道它是对象的变量。

使用undefined设置混合类型的变量。


这是我对 5 个原语和对象类型的用法,解释了 undefinednull 的“用例”之间的区别。

String

如果你知道一个变量在整个生命周期中只是一个字符串,按照惯例,你可以将它初始化为 "":

("") ? true : false; // false
typeof ""; // "string";
("Hello World") ? true : false; // true
typeof "Hello World"; // "string"

Number

如果你知道变量只是一个数字,而在整个生命周期中,按照惯例,您可以将其初始化为 0 (如果 0 是一个重要的值,则为 NaN值):

(0) ? true : false; // false
typeof 0; // "number";
(16) ? true : false; // true
typeof 16; // "number"

(NaN) ? true : false; // false
typeof NaN; // "number";
(16) ? true : false; // true
typeof 16; // "number"

Boolean

如果您知道变量在整个生命周期中只是布尔值,按照惯例,您可以将其初始化为 false

(false) ? true : false; // false
typeof false; // "boolean";
(true) ? true : false; // true
typeof true; // "boolean"

Object

如果您知道变量在整个生命周期中只是一个对象,按照惯例,您可以将其初始化为 null

(null) ? true : false; // false
typeof null; // "object";
({}) ? true : false; // true
typeof {}; // "object"

注意:null 的明智用法是 <对象的strong>falsy版本,因为对象始终为true,并且因为typeof null返回object。这意味着 typeof myVarObject 为 Object 和 null 类型返回一致的值。

全部

如果您知道变量具有混合类型(所有生命周期中的任何类型),按照惯例,您可以将其初始化为undefined

tl;dr

Use null for set a variable you know it is an Object.

Use undefined for set a variable whose type is mixed.


This is my usage of both 5 primitives and Object type, and that explain the difference between « use case » of undefined or null.

String

If you know a variable is only a string while all lifecycle, by convention, you could initialize it, to "":

("") ? true : false; // false
typeof ""; // "string";
("Hello World") ? true : false; // true
typeof "Hello World"; // "string"

Number

If you know a variable is only a number while all lifecycle, by convention, you could initialize it, to 0 (or NaN if 0 is an important value in your usage):

(0) ? true : false; // false
typeof 0; // "number";
(16) ? true : false; // true
typeof 16; // "number"

or

(NaN) ? true : false; // false
typeof NaN; // "number";
(16) ? true : false; // true
typeof 16; // "number"

Boolean

If you know a variable is only a boolean while all lifecycle, by convention, you could initialize it, to false:

(false) ? true : false; // false
typeof false; // "boolean";
(true) ? true : false; // true
typeof true; // "boolean"

Object

If you know a variable is only an Object while all lifecycle, by convention, you could initialize it, to null:

(null) ? true : false; // false
typeof null; // "object";
({}) ? true : false; // true
typeof {}; // "object"

Note: the smart usage off null is to be the falsy version of an Object because an Object is always true, and because typeof null return object. That means typeof myVarObject return consistent value for both Object and null type.

All

If you know a variable has a mixed type (any type while all lifecycle), by convention, you could initialize it, to undefined.

殤城〤 2024-10-25 16:29:31

除了不同的含义之外,还有其他差异:

  1. 对象解构对于这两个值的工作方式不同:
    const { a = "default" } = { a: undefined }; // a 是“默认”
    const { b = "默认" } = { b: null }; // b 为空
    
  2. JSON.stringify() 保留 null 但省略 undefined
    const json = JSON.stringify({ undefinedValue: undefined, nullValue: null });
    控制台.log(json); // 打印 {"nullValue":null}
    
  3. typeof 运算符
    console.log(typeof undefined); // “不明确的”
    console.log(typeof null); // “对象”而不是“空”
    

In addition to a different meaning there are other differences:

  1. Object destructuring works differently for these two values:
    const { a = "default" } = { a: undefined }; // a is "default"
    const { b = "default" } = { b: null };      // b is null
    
  2. JSON.stringify() keeps null but omits undefined
    const json = JSON.stringify({ undefinedValue: undefined, nullValue: null });
    console.log(json); // prints {"nullValue":null}
    
  3. typeof operator
    console.log(typeof undefined); // "undefined"
    console.log(typeof null);      // "object" instead of "null"
    
水波映月 2024-10-25 16:29:31

JavaScript 中有 5 种基本数据类型:String、Number、Boolean、null 和 undefined。
我将尝试用一些简单的例子来解释。

假设我们有一个简单的函数

 function test(a) {
     if(a == null) {
        alert("a is null");
     } else {
        alert("The value of a is " + a);
     }
  }

,此外,上面的函数 if(a == null) 与 if(!a) 相同。

现在,当我们在不传递参数 a 的情况下调用这个函数时

test(); // will alert "a is null";
test(4); // will alert "The value of a is " + 4;

var a;
alert(typeof a);

这也会给出 undefined;我们已经声明了一个变量,但我们还没有为该变量分配任何值;

但如果我们

var a = null;
alert(typeof a); // will give alert as object

这样写 null 就是一个对象。在某种程度上,我们为“a”分配了一个 null 值

In JavasScript there are 5 primitive data types: String, Number, Boolean, null and undefined.
I will try to explain with some simple examples.

Let's say we have a simple function

 function test(a) {
     if(a == null) {
        alert("a is null");
     } else {
        alert("The value of a is " + a);
     }
  }

Also, in above function if(a == null) is the same as if(!a).

Now when we call this function without passing the parameter a

test(); // will alert "a is null";
test(4); // will alert "The value of a is " + 4;

also

var a;
alert(typeof a);

This will give undefined; we have declared a variable but we have not asigned any value to this variable;

but if we write

var a = null;
alert(typeof a); // will give alert as object

so null is an object. In a way we have assigned a value null to 'a'

め七分饶幸 2024-10-25 16:29:31

当您在 JavaScript 中声明变量时,它会被赋予值 undefined。这意味着该变量未受影响,并且可以在将来分配任何值。它还意味着您不知道该变量在声明时将保存的值。

现在您可以显式分配一个变量 null。这意味着该变量没有任何值。例如 - 有些人没有中间名。因此,在这种情况下,最好将值 null 分配给 person 对象的 middlename 变量。

现在假设有人正在访问您的 person 对象的 middlename 变量,并且它的值为 undefined。他不知道开发人员是否忘记初始化该变量或者它是否没有任何值。如果它的值为 null,那么用户可以轻松推断 middlename 没有任何值,并且它不是一个未更改的变量。

When you declare a variable in javascript, it is assigned the value undefined. This means the variable is untouched and can be assigned any value in future. It also implies that you don't know the value that this variable is going to hold at the time of declaration.

Now you can explicitly assign a variable null. It means that the variable does not have any value. For example - Some people don't have a middle name. So in such a case its better to assign the value null to the middlename variable of a person object.

Now suppose that someone is accessing the middlename variable of your person object and it has the value undefined. He wouldn't know if the developer forgot to initialize this variable or if it didn't have any value. If it has the value null, then the user can easily infer that middlename doesn't have any value and it is not an untouched variable.

累赘 2024-10-25 16:29:31

好吧,当我们听到 nullundefined 时,我们可能会感到困惑,但让我们从简单的开始,它们都是 falsy 并且在很多方面都很相似,但是 JavaScript 的奇怪部分,使它们有一些显着的差异,例如, typeof null'object'typeof 未定义'未定义'

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

但是,如果您使用 == 检查它们,如下所示,您会发现它们都是 falsy

null==undefined; //true

此外,您还可以将 null 分配给对象属性或一个原语,而 undefined 可以通过不分配任何东西来简单地实现。

我创建了一个快速图像,让您一目了然地显示差异。

空且未定义

OK, we may get confused when we hear about null and undefined, but let's start it simple, they both are falsy and similar in many ways, but weird part of JavaScript, make them a couple of significant differences, for example, typeof null is 'object' while typeof undefined is 'undefined'.

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

But if you check them with == as below, you see they are both falsy:

null==undefined; //true

Also you can assign null to an object property or to a primitive, while undefined can simply be achieved by not assigning to anything.

I create a quick image to show the differences for you at a glance.

Null and Undefined

泪眸﹌ 2024-10-25 16:29:31

对于 undefined 类型,只有一个值:undefined

对于 null 类型,只有一个值:null

因此对于它们两者来说,标签既是它的类型又是它的值。

它们之间的区别。例如:

  • null 是一个空值
  • undefined 是一个缺失值

或者:

  • undefined 还没有值
  • null 曾经有一个值,但现在不再有值了。

实际上,null 是一个特殊关键字,而不是标识符,因此您不能将其视为要分配的变量。

但是,undefined 是一个标识符。但是,在非严格 模式和严格 模式下,您都可以创建名称为 undefined 的局部变量。但这是一个糟糕的想法!

function foo() {
    undefined = 2; // bad idea!
}

foo();

function foo() {
    "use strict";
    undefined = 2; // TypeError!
}

foo();

For the undefined type, there is one and only one value: undefined.

For the null type, there is one and only one value: null.

So for both of them, the label is both its type and its value.

The difference between them. For example:

  • null is an empty value
  • undefined is a missing value

Or:

  • undefined hasn't had a value yet
  • null had a value and doesn't anymore

Actually, null is a special keyword, not an identifier, and thus you cannot treat it as a variable to assign to.

However, undefined is an identifier. In both non-strict mode and strict mode, however, you can create a local variable of the name undefined. But this is one terrible idea!

function foo() {
    undefined = 2; // bad idea!
}

foo();

function foo() {
    "use strict";
    undefined = 2; // TypeError!
}

foo();
甜尕妞 2024-10-25 16:29:31

我想添加一个知识点,涉及nullundefined之间的细微差别。当您尝试从头开始学习 Vanilla JavaScript(JS) 时,了解这一点是很有必要的:

null 是 JS 中的保留关键字,而 undefined 是 JS 中的属性
您所在的运行时环境的全局对象。

在编写代码时,这种差异无法识别,因为 nullundefined 始终用在右侧( JavaScript 语句的 RHS)。但是,当您在表达式的左侧 (LHS) 使用它们时,您可以轻松观察到这种差异。因此 JS 解释器将以下代码解释为错误:

var null = 'foo'

它给出以下错误:

未捕获的语法错误:意外的标记为空

同时,下面的代码成功运行,尽管我不建议在现实生活中这样做:

var undefined = 'bar'

这有效,因为 undefined 是全局对象上的一个属性 (window 对象(如果 JavaScript 在浏览器中运行)

I want to add a knowledge point which pertains to a subtle difference between null and undefined. This is good to know when you are trying to learn Vanilla JavaScript(JS) from ground up:

null is a reserved keyword in JS while undefined is a property on
the global object of the run-time environment you're in.

While writing code, this difference is not identifiable as both null and undefined are always used in right hand side (RHS) of a JavaScript statement. But when you use them in left hand side (LHS) of an expression then you can observe this difference easily. So JS interpreter interprets the below code as error:

var null = 'foo'

It gives below error:

Uncaught SyntaxError: Unexpected token null

At the same time, below code runs successfully although I won't recommend doing so in real life:

var undefined = 'bar'

This works because undefined is a property on the global object (window object in case of JavaScript running in a browser)

半窗疏影 2024-10-25 16:29:31

null 和 undefined 都用来表示某些值的缺失。

var a = null;

a 被初始化并定义。

typeof(a)
//object

null 是 JavaScript 中的一个对象

Object.prototype.toString.call(a) // [object Object]

var b;

b 是未定义的,未初始化的

未定义对象属性也是未定义的。例如,“x”未在对象 c 上定义,如果您尝试访问 cx,它将返回 undefined。

通常我们将 null 分配给未定义的变量。

null and undefined are both are used to represent the absence of some value.

var a = null;

a is initialized and defined.

typeof(a)
//object

null is an object in JavaScript

Object.prototype.toString.call(a) // [object Object]

var b;

b is undefined and uninitialized

undefined object properties are also undefined. For example "x" is not defined on object c and if you try to access c.x, it will return undefined.

Generally we assign null to variables not undefined.

无声情话 2024-10-25 16:29:31

根据 Ryan Morr 关于此主题的详尽文章...

“通常,如果您需要为变量或属性分配非值、将其传递给函数或从函数返回它,则 null 几乎总是最佳选择。简而言之,JavaScript 使用 undefined,程序员应该使用 null。”

请参阅探索空与未定义的永恒深渊

Per Ryan Morr's thorough article on this subject...

"Generally, if you need to assign a non-value to a variable or property, pass it to a function, or return it from a function, null is almost always the best option. To put it simply, JavaScript uses undefined and programmers should use null."

See Exploring the Eternal Abyss of Null and Undefined

笑忘罢 2024-10-25 16:29:31

在 javascript 中,所有变量都存储为键值对。每个变量都存储为变量名:变量值/引用

未定义表示变量已在内存中分配了空间,但没有为其分配任何值。作为最佳实践,您不应使用此类型作为作业。

在这种情况下,如何表示您希望变量在代码稍后的位置没有值?您可以使用类型
null ,这也是一种类型,用于定义相同的事物,即没有值,但它与 undefined 不同,因为在这种情况下,您实际上在内存中拥有该值。该值为 null

两者相似,但用法和含义不同。

In javascript all variables are stored as key value pairs. Each variable is stored as variable_name : variable_value/reference.

undefined means a variable has been given a space in memory, but no value is assigned to it. As a best practice, you should not use this type as an assignment.

In that case how to denote when you want a variable to be without value at a later point in the code? You can use the type
null ,which is also a type that is used to define the same thing, absence of a value, but it is not the same as undefined, as in this case you actually have the value in memory. That value is null

Both are similar but usage and meaning are different.

断念 2024-10-25 16:29:31

undefined 和 null 之间的含义差异是 JavaScript 设计的一个意外,大多数时候并不重要。如果您实际上必须关心这些值,我建议将它们视为大部分可以互换的。

来自Eloquent Javascript一书

The difference in meaning between undefined and null is an accident of JavaScript’s design, and it doesn’t matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable.

From the Eloquent Javascript book

风铃鹿 2024-10-25 16:29:31

由于 typeof 返回 undefined,undefined 是一种类型,其中 null 是初始化器,表示该变量不指向任何对象(实际上 Javascript 中的所有内容都是对象)。

As typeof returns undefined, undefined is a type where as null is an initializer indicates the variable points to no object(virtually everything in Javascript is an object).

毁梦 2024-10-25 16:29:31

null - 它是一个赋值值,与变量一起使用表示没有值(它是一个对象)。

未定义 - 这是一个没有分配任何值的变量,因此 JavaScript 会为其分配一个未定义的值(它是一种数据类型)。

未声明 - 如果变量根本没有创建,则称为未声明。

null - It is an assignment value, which is used with variable to represent no value (it's an object).

undefined - It is a variable which does not have any value assigned to it, so JavaScript will assign an undefined to it (it's a data type).

undeclared - If a variable is not created at all, it is known as undeclared.

煞人兵器 2024-10-25 16:29:31

看看这个。输出值千字。

var b1 = document.getElementById("b1");

checkif("1, no argument"                        );
checkif("2, undefined explicitly",     undefined);
checkif("3, null explicitly",               null);
checkif("4, the 0",                            0);
checkif("5, empty string",                    '');
checkif("6, string",                    "string");
checkif("7, number",                      123456);

function checkif (a1, a2) {
	print("\ncheckif(), " + a1 + ":");
	if (a2 == undefined) {
		print("==undefined:    YES");
	} else {
		print("==undefined:    NO");
	}
	if (a2 === undefined) {
		print("===undefined:   YES");
	} else {
		print("===undefined:   NO");
	}
	if (a2 == null) {
		print("==null:         YES");
	} else {
		print("==null:         NO");
	}
	if (a2 === null) {
		print("===null:        YES");
	} else {
		print("===null:        NO");
	}
	if (a2 == '') {
		print("=='':           YES");
	} else {
		print("=='':           NO");
	}
	if (a2 === '') {
		print("==='':          YES");
	} else {
		print("==='':          NO");
	}
	if (isNaN(a2)) {
		print("isNaN():        YES");
	} else {
		print("isNaN():        NO");
	}
	if (a2) {
		print("if-?:           YES");
	} else {
		print("if-?:           NO");
	}
		print("typeof():       " + typeof(a2));
}

function print(v) {
	b1.innerHTML += v + "\n";
}
<!DOCTYPE html>
<html>
<body>
<pre id="b1"></pre>
</body>
</html>

另请参阅:

干杯!

Check this out. The output is worth thousand words.

var b1 = document.getElementById("b1");

checkif("1, no argument"                        );
checkif("2, undefined explicitly",     undefined);
checkif("3, null explicitly",               null);
checkif("4, the 0",                            0);
checkif("5, empty string",                    '');
checkif("6, string",                    "string");
checkif("7, number",                      123456);

function checkif (a1, a2) {
	print("\ncheckif(), " + a1 + ":");
	if (a2 == undefined) {
		print("==undefined:    YES");
	} else {
		print("==undefined:    NO");
	}
	if (a2 === undefined) {
		print("===undefined:   YES");
	} else {
		print("===undefined:   NO");
	}
	if (a2 == null) {
		print("==null:         YES");
	} else {
		print("==null:         NO");
	}
	if (a2 === null) {
		print("===null:        YES");
	} else {
		print("===null:        NO");
	}
	if (a2 == '') {
		print("=='':           YES");
	} else {
		print("=='':           NO");
	}
	if (a2 === '') {
		print("==='':          YES");
	} else {
		print("==='':          NO");
	}
	if (isNaN(a2)) {
		print("isNaN():        YES");
	} else {
		print("isNaN():        NO");
	}
	if (a2) {
		print("if-?:           YES");
	} else {
		print("if-?:           NO");
	}
		print("typeof():       " + typeof(a2));
}

function print(v) {
	b1.innerHTML += v + "\n";
}
<!DOCTYPE html>
<html>
<body>
<pre id="b1"></pre>
</body>
</html>

See also:

Cheers!

吃不饱 2024-10-25 16:29:31

一般来说 – 不要使用 null 以避免混淆。

  1. 标准库方法返回 undefined,而不是 null
let a = [10];
console.log(a[1]) //=> undefined
console.log(a.find(value => value === 5)) //=> undefined
  1. 我经常在人们的代码中看到某些变量首先是 undefined,然后分配给某个值,然后通过设置为 null 来清除。这不一致,最好设置回 undefined

尽管如此,如果框架使用它,或者用于 json 序列化,null 仍然有意义。

Generally – don't use null to avoid confusion.

  1. Standard library methods return undefined, not null
let a = [10];
console.log(a[1]) //=> undefined
console.log(a.find(value => value === 5)) //=> undefined
  1. I see often in people's code that some variable was undefined at first, then assigned to some value, then cleared by setting to null. That's not consistent, better to set back to undefined.

Still, null makes sense if framework uses it, or for json serialization.

暮光沉寂 2024-10-25 16:29:31

undefinednull 之间的差异很小,但还是有区别的。值为未定义的变量从未被初始化。值为 null 的变量被显式指定为 null 值,这意味着该变量被显式设置为没有值。如果使用 null==undefined 表达式比较 undefinednull,它们将相等。

The difference between undefined and null is minimal, but there is a difference. A variable whose value is undefined has never been initialized. A variable whose value is null was explicitly given a value of null, which means that the variable was explicitly set to have no value. If you compare undefined and null by using the null==undefined expression, they will be equal.

缪败 2024-10-25 16:29:31

基本上,未定义是javascript在运行时创建的全局变量,无论null是否意味着没有值分配给该变量(实际上null本身就是一个对象)。

让我们举个例子:

        var x;  //we declared a variable x, but no value has been assigned to it.
        document.write(x) //let's print the variable x

未定义,这就是您将得到的输出。

现在,

        x=5;
        y=null;
        z=x+y;

您将得到 5 作为输出。这是未定义null之间的主要区别

Basically, Undefined is a global variable that javascript create at the run time whether null means that no value has assigned to the variable (actually null is itself an object).

Let's take an example:

        var x;  //we declared a variable x, but no value has been assigned to it.
        document.write(x) //let's print the variable x

Undefined that's what you will get as output.

Now,

        x=5;
        y=null;
        z=x+y;

and you will get 5 as output. That's the main difference between the Undefined and null

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