在 JavaScript 中使用 null 而不是 undefined 的原因是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6604749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:27:35  来源:igfitidea点击:

What reason is there to use null instead of undefined in JavaScript?

javascriptnullundefined

提问by Jimmy Cuadra

I've been writing JavaScript for quite a long time now, and I have never had a reason to use null. It seems that undefinedis always preferable and serves the same purpose programmatically. What are some practical reasons to use nullinstead of undefined?

我已经写 JavaScript 很长时间了,我从来没有理由使用null. 这似乎undefined总是更可取,并且以编程方式服务于相同的目的。使用null代替 的一些实际原因是undefined什么?

采纳答案by B T

Null and undefined are essentially two different values that mean the same thing. The only difference is in the conventionsof how you use them in yoursystem. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.

Null 和 undefined 本质上是两个不同的值,它们表示同一件事。唯一的区别是在约定的你如何使用它们系统。正如一些人所提到的,有些人使用 null 表示“没有对象”,有时您可能会得到一个对象,而 undefined 意味着没有预期的对象(或存在错误)。我的问题是它完全任意,完全没有必要。

That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are alwaysundefined.

也就是说,有一个主要区别 - 未初始化的变量(包括未传递参数的函数参数等)始终未定义。

Which is why in my code I neveruse null unless something I don't control returns null (regex matching for example). The beauty of this is it simiplifies things a lot. I never have to check if x === undefined || x === null. And if you're in the habit of using == or simply stuff like if(x) ... . Stop it. !xwill evaluate to true for an empty string, 0, null, NaN - ie things you probably don't want. If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.

这就是为什么在我的代码中我从不使用 null 除非我无法控制的东西返回 null (例如正则表达式匹配)。这样做的好处在于它简化了很多事情。我永远不必检查 x === undefined || x === 空。如果您习惯于使用 == 或只是像 if(x) ... 之类的东西。停下来。!x对于空字符串、0、null、NaN,将评估为真 - 即您可能不想要的东西。如果您想编写不糟糕的 javascript,请始终使用三重等号 === 并且永远不要使用 null(使用 undefined 代替)。它会让你的生活更轻松。

回答by bbg

I don't really have an answer, but according to Nicholas C. Zakas, page 30 of his book "Professional JavaScript for Web Developers":

我真的没有答案,但根据Nicholas C. Zakas在他的书Professional JavaScript for Web Developers第 30 页的说法:

When defining a variable that is meant to later hold an object, it is advisable to initialize the variable to nullas opposed to anything else. That way, you can explicitly check for the value nullto determine if the variable has been filled with an object reference at a later time

当定义一个以后要保存对象的变量时,建议将变量初始化null为与其他任何对象相反的值。这样,您可以显式检查该值null以确定该变量是否已在以后填充了对象引用

回答by Yaplex

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 has no value.

未定义是不存在事物概念的地方;它没有类型,并且在该范围内之前从未被引用过;null 是已知事物存在的地方,但它没有价值。

回答by Govind Rai

At the end of the day, because both nulland undefinedcoerce to the same value (Boolean(undefined) === false && Boolean(null) === false), you can technically use either to get the job done. However, there is right way, IMO.

归根结底,因为null和 都undefined强制为相同的值 ( Boolean(undefined) === false && Boolean(null) === false),所以从技术上讲,您可以使用任何一个来完成工作。但是,有正确的方法,IMO。

  1. Leave the usage of undefinedto the JavaScript compiler.

    undefinedis used to describe variables that do not point to a reference. It is something that the JS compiler will take care for you. At compile time the JS engine will set the value of all hoisted variables to undefined. As the engine steps through the code and values becomes available the engine will assign respective values to respective variables. For those variables for whom it did not find values, the variables would continue to maintain a reference to the primitive undefined.

  2. Only use null if you explicitly want to denote the value of a variable as having "no value".

    As @com2gz states: nullis used to define something programmatically empty. undefinedis meant to say that the reference is not existing. A nullvalue has a defined reference to "nothing". If you are calling a non-existing property of an object, then you will get undefined. If I would make that property intentionally empty, then it must be nullso you know that it's on purpose.

  1. 将 的用法留给undefinedJavaScript 编译器。

    undefined用于描述不指向引用的变量。这是 JS 编译器会照顾你的事情。在编译时,JS 引擎会将所有提升的变量的值设置为undefined. 当引擎逐步执行代码并且值变得可用时,引擎会将相应的值分配给相应的变量。对于那些没有找到值的变量,这些变量将继续维护对原语的引用undefined

  2. 仅当您明确希望将变量的值表示为“无值”时才使用 null。

    正如@com2gz 所说:null用于以编程方式定义空的东西。undefined意思是说引用不存在。一个null价值有一个定义的参考,以“无”。如果您正在调用对象的不存在的属性,那么您将获得undefined. 如果我有意让该属性为空,那么它必须是null为了让您知道它是故意的。

TLDR;Don't use the undefinedprimitive. It's a value that the JS compiler will automatically set for you when you declare variables without assignment or if you try to access properties of objects for which there is no reference. On the other hand, use nullif and only if you intentionally want a variable to have "no value".

TLDR;不要使用undefined原语。当您在没有赋值的情况下声明变量或尝试访问没有引用的对象的属性时,JS 编译器会自动为您设置一个值。另一方面,null当且仅当您有意希望变量“没有值”时才使用。

I never explicitly set anything to undefined (and I haven't come across this in the many codebases I've interacted with). Also, I rarely use null. The only times I use nullis when I want to denote the value of an argument to a function as having no value, i.e.,:

我从未明确将任何内容设置为未定义(并且在我与之交互的许多代码库中都没有遇到过这种情况)。此外,我很少使用null. 我唯一使用null的时候是当我想将函数的参数值表示为没有值时,即:

function printArguments(a,b) {
  console.log(a,b);
}

printArguments(null, " hello") // logs: null hello

回答by thdoan

Everyone has their own way of coding and their own internal semantics, but over the years I have found this to be the most intuitive advice that I give people who ask this question: when in doubt, do what JavaScript does.

每个人都有自己的编码方式和自己的内部语义,但多年来我发现这是我给提出这个问题的人最直观的建议:当有疑问时,做 JavaScript 所做的

Let's say you are working with object properties like options for a jQuery plugin...ask yourself what value JavaScript gives a property that has yet to be defined -- the answer is undefined. So in this context, I would initialize these types of things with 'undefined' to be consistent with JavaScript (for variables, you can do var myVar;instead of var myVar = undefined;).

假设您正在处理对象属性,例如 jQuery 插件的选项……问问自己 JavaScript 赋予尚未定义的属性什么值 - 答案是undefined. 因此,在这种情况下,我会使用 'undefined' 来初始化这些类型的东西以与 JavaScript 保持一致(对于变量,您可以使用var myVar;代替var myVar = undefined;)。

Now let's say you are doing DOM manipulation...what value does JavaScript assign to non-existent elements? The answer is null. This is the value I would initialize with if you are creating a placeholder variable that will later hold a reference to an element, document fragment, or similar that relates to the DOM.

现在假设你正在做 DOM 操作……JavaScript 为不存在的元素分配什么值?答案是null。如果您正在创建一个占位符变量,该变量稍后将保存对元素、文档片段或与 DOM 相关的类似内容的引用,那么我将使用该值进行初始化。

If you're working with JSON, then a special case needs to be made: for undefined property values, you should either set them to ""or nullbecause a value of undefinedis not considered proper JSON format.

如果您正在使用 JSON,则需要进行特殊情况处理:对于未定义的属性值,您应该将它们设置为""null因为值undefined不被视为正确的 JSON 格式。

With this said, as a previous poster has expressed, if you find that you're initializing stuff with nullor undefinedmore than once in a blue moon, then maybe you should reconsider how you go about coding your app.

话虽如此,正如之前的一位海报所表达的那样,如果您发现自己在蓝色月亮中使用nullundefined多次初始化东西,那么也许您应该重新考虑如何编写应用程序。

回答by RobG

You might adopt the convention suggested here, but there really is no good reason to. It is not used consistently enough to be meaningful.

您可能会采用此处建议的约定,但确实没有充分的理由。它的使用不够一致,不足以使其有意义。

In order to make the convention useful, you first must know that the called function follows the convention. Then you have to explicitly test the returned value and decide what to do. If you get undefined, you can assume that some kind of error occurred that the called function knew about. But if an error happened, and the function knew about it, and it is useful to send that out into the wider environment, why not use an error object? i.e. throw an error?

为了使约定有用,您首先必须知道被调用的函数遵循约定。然后您必须显式测试返回值并决定要做什么。如果得到undefined,则可以假设发生了被调用函数知道的某种错误。但是如果发生了错误,并且函数知道它,并且将其发送到更广泛的环境中很有用,为什么不使用错误对象呢?即抛出错误?

So at the end of the day, the convention is practically useless in anything other than very small programs in simple environments.

因此,归根结底,除了简单环境中的非常小的程序之外,该约定实际上没有用处。

回答by Faccion

A useful property in nullthat undefineddoes not qualifies:

null中一个有用的属性undefined不符合条件:

> null + 3
3
> undefined + 3
NaN

I use nullwhen I want to 'turn off' a numeric value, or to initialize some. My last use was manipulating css transform:

null当我想“关闭”一个数值或初始化一些数值时使用。我最后一次使用是操纵 css 变换:

const transforms = { perspective : null, rotateX : null };
// if already set, increase, if not, set to x
runTimeFunction((x) => { trasforms.perspective += x; });
// still useful, as setting perspective to 0 is different than turning it off
runTimeFunction2((x) => { transforms.perspective = null; });

// toCss will check for 'null' values and not set then at all
runTimeFunction3(() => { el.style.transform = toCss(transforms); });

Not sure if I shoulduse this property thought...

不知道我是否应该使用这个属性认为......

回答by kennebec

DOM nodes and elements are not undefined, but may be null.

DOM 节点和元素不是未定义的,但可能为空。

  • The nextSibling of the last child of an element is null.

  • The previousSibling of the first child is null.

  • A document.getElementById reference is null if the element does not exist in the document.

  • 元素最后一个子元素的 nextSibling 为 null。

  • 第一个孩子的 previousSibling 为空。

  • 如果文档中不存在该元素,则 document.getElementById 引用为 null。

But in none of these cases is the value undefined; there just is no node there.

但在这些情况下,值都不是undefined;那里只是没有节点。

回答by Matt Way

A few have said that it is ok to initialise objects to null. I just wanted to point out that destructuring argument defaults don't work with null. For example:

一些人说可以将对象初始化为null. 我只是想指出解构参数默认值不适用于null. 例如:

const test = ({ name } = {}) => {
  console.log(name)
}

test() // logs undefined
test(null) // throws error

This requires performing nullchecks priorto calling the function which may happen often.

这需要调用可能经常发生的函数之前执行null检查。

回答by lilbitofchee

Just wanna add that with usage of certain javascript libraries, null and undefined can have unintended consequences.

只是想补充一点,使用某些 javascript 库, null 和 undefined 可能会产生意想不到的后果。

For example, lodash's getfunction, which accepts a default value as a 3rd argument:

例如,lodash 的get函数,它接受一个默认值作为第三个参数:

const user = {
  address: {
    block: null,
    unit: undefined,
  }
}
console.log(_.get(user, 'address.block', 'Default Value')) // prints null
console.log(_.get(user, 'address.unit', 'Default Value')) // prints 'Default Value'
console.log(_.get(user, 'address.postalCode', 'Default Value')) // prints 'Default Value'

Another example: If you use defaultProps in React, if a property is passed null, default props are not used because null is interpreted as a defined value. e.g.

另一个例子:如果你在 React 中使用 defaultProps,如果传递了一个属性null,默认的 props 不会被使用,因为null 被解释为一个定义的值。例如

class MyComponent extends React.Component {
   static defaultProps = {
      callback: () => {console.log('COMPONENT MOUNTED')},
   }
   componentDidMount() {
      this.props.callback();
   }
}
//in some other component
<MyComponent />   // Console WILL print "COMPONENT MOUNTED"
<MyComponent callback={null}/>   // Console will NOT print "COMPONENT MOUNTED"
<MyComponent callback={undefined}/>   // Console WILL print "COMPONENT MOUNTED"