简体   繁体   English

有什么理由在 JavaScript 中使用 null 而不是 undefined?

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

I've been writing JavaScript for quite a long time now, and I have never had a reason to use null .我已经写 JavaScript 很长时间了,我从来没有理由使用null It seems that undefined is always preferable and serves the same purpose programmatically.似乎undefined总是更可取,并且以编程方式服务于相同的目的。 What are some practical reasons to use null instead of undefined ?使用null而不是undefined的一些实际原因是什么?

I don't really have an answer, but according to Nicholas C.我真的没有答案,但根据Nicholas C 的说法。 Zakas , page 30 of his book " Professional JavaScript for Web Developers " : Zakas ,他的书Web 开发人员的专业 JavaScript的第 30 页:

When defining a variable that is meant to later hold an object, it is advisable to initialize the variable to null as opposed to anything else.当定义一个打算稍后保存 object 的变量时,建议将变量初始化为null而不是其他任何东西。 That way, you can explicitly check for the value null to determine if the variable has been filled with an object reference at a later time这样,您可以稍后显式检查值null以确定变量是否已填充 object 引用

null and undefined are essentially two different values that mean the same thing. nullundefined本质上是两个不同的值,它们的含义相同。 The only difference is in the conventions of how you use them in your system.唯一的区别在于如何在系统中使用它们的约定 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).正如一些人所提到的,有些人使用null来表示“无对象”,有时您可能会得到 object 而未定义意味着没有 object 是预期的(或存在错误)。 My problem with that is its completely arbitrary, and totally unnecessary.我的问题是它完全武断,完全没有必要。

That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.也就是说,有一个主要区别 - 未初始化的变量(包括未传递参数的 function 参数等)始终未定义。

Which is why in my code I never use null unless something I don't control returns null (regex matching for example).这就是为什么在我的代码中我从不使用 null 除非我无法控制的东西返回 null (例如正则表达式匹配)。 The beauty of this is it simplifies things a lot.这样做的好处是它简化了很多事情。 I never have to check if x === undefined || x === null我永远不必检查x === undefined || x === null x === undefined || x === null , I can just check x === undefined . x === undefined || x === null ,我可以检查x === undefined And if you're in the habit of using == or simply stuff like if(x)... , stop it.如果你习惯使用==或者只是if(x)...之类的东西,请停止它。

!x will evaluate to true for an empty string, 0 , null , NaN - ie things you probably don't want. !x对于空字符串0nullNaN将评估为 true - 即您可能不想要的东西。 If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead).如果您想编写不糟糕的 javascript,请始终使用三等号===并且永远不要使用null (改用undefined )。 It'll make your life way easier.它会让你的生活更轻松。

At the end of the day, because both null and undefined coerce to the same value ( Boolean(undefined) === false && Boolean(null) === false ), you can technically use either to get the job done.归根结底,因为nullundefined都强制转换为相同的值( Boolean(undefined) === false && Boolean(null) === false ),所以从技术上讲,您可以使用其中任何一个来完成工作。 However, there is right way, IMO.但是,有正确的方法,IMO。

  1. Leave the usage of undefined to the JavaScript compiler.undefined的用法留给 JavaScript 编译器。

    undefined is used to describe variables that do not point to a reference. undefined用于描述不指向引用的变量。 It is something that the JS compiler will take care for you.这是 JS 编译器会为您处理的事情。 At compile time the JS engine will set the value of all hoisted variables to undefined .在编译时,JS 引擎会将所有提升变量的值设置为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 .对于那些没有找到值的变量,这些变量将继续保持对原语undefined的引用。

  2. Only use null if you explicitly want to denote the value of a variable as having "no value".如果您明确想要将变量的值表示为“无值”,则仅使用 null。

    As @com2gz states: null is used to define something programmatically empty.正如@com2gz 所说: null用于以编程方式定义一些空的东西。 undefined is meant to say that the reference is not existing. undefined表示引用不存在。 A null value has a defined reference to "nothing". null值定义了对“无”的引用。 If you are calling a non-existing property of an object, then you will get undefined .如果您正在调用 object 的不存在属性,那么您将得到undefined If I would make that property intentionally empty, then it must be null so you know that it's on purpose.如果我故意使该属性为空,那么它必须是null所以你知道它是故意的。

TLDR; TLDR; Don't use the undefined primitive.不要使用undefined的原语。 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.当您声明没有赋值的变量或尝试访问没有引用的对象的属性时,JS 编译器会自动为您设置一个值。 On the other hand, use null if and only if you intentionally want a variable to have "no value".另一方面,当且仅当您有意希望变量具有“无值”时,才使用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 .另外,我很少使用null The only times I use null is when I want to denote the value of an argument to a function as having no value, ie,:我使用null的唯一时间是当我想将 function 的参数值表示为没有值时,即:

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

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

undefined is where no notion of the thing exists; undefined 是不存在事物概念的地方; it has no type, and it's never been referenced before in that scope;它没有类型,并且之前从未在 scope 中被引用过; null is where the thing is known to exist, but it has no value. null 是已知事物存在的地方,但没有任何价值。

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 .假设您正在使用 object 属性,例如 jQuery 插件的选项...问问自己 JavaScript 给出的属性尚未定义的值是什么——答案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; ).因此,在这种情况下,我将使用 '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?现在假设您正在进行 DOM 操作...... JavaScript 分配给不存在的元素什么值? The answer is null .答案是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 相关的元素、文档片段或类似内容的引用,我将使用此值进行初始化。

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 null because a value of undefined is not considered proper JSON format.如果您使用 JSON,则需要进行特殊情况:对于未定义的属性值,您应该将它们设置为""null ,因为undefined的值不被认为是正确的 Z0ECD11C1D7A2877401DZ48A23 格式。

With this said, as a previous poster has expressed, if you find that you're initializing stuff with null or undefined more than once in a blue moon, then maybe you should reconsider how you go about coding your app.话虽如此,正如之前的海报所表达的那样,如果你发现你正在用nullundefined在蓝月亮中多次初始化,那么也许你应该重新考虑你如何 go 来编码你的应用程序。

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.为了使约定有用,您首先必须知道被调用的 function 遵循约定。 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 .如果你得到undefined ,你可以假设发生了某种被称为 function 知道的错误。 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?但是,如果发生错误,并且 function 知道它,并且将其发送到更广泛的环境中很有用,为什么不使用错误 object 呢? ie throw an error?即抛出错误?

So at the end of the day, the convention is practically useless in anything other than very small programs in simple environments.因此,归根结底,除了简单环境中的非常小的程序之外,该约定实际上毫无用处。

A few have said that it is ok to initialise objects to null .一些人说可以将对象初始化为null I just wanted to point out that destructuring argument defaults don't work with null .我只是想指出解构参数默认值不适用于null For example:例如:

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

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

This requires performing null checks prior to calling the function which may happen often.这需要在调用 function之前执行null检查,这可能经常发生。

A useful property in null that undefined does not qualifies: null中一个有用的属性undefined不符合条件:

> null + 3
3
> undefined + 3
NaN

I use null when I want to 'turn off' a numeric value, or to initialize some.当我想“关闭”一个数值或初始化一些数值时,我使用null My last use was manipulating css transform:我最后一次使用的是操作 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 should use this property thought...不知道我是否应该使用这个属性的想法......

DOM nodes and elements are not undefined, but may be null. DOM 节点和元素不是未定义的,但可能是 null。

  • The nextSibling of the last child of an element is null.元素的最后一个子元素的 nextSibling 是 null。

  • The previousSibling of the first child is null.第一个孩子的前一个兄弟姐妹是 null。

  • A document.getElementById reference is null if the element does not exist in the document.如果文档中不存在该元素,则 document.getElementById 引用为 null。

But in none of these cases is the value undefined ;但在这些情况下,值都不是undefined there just is no node there.那里没有节点。

In JavaScript, the value null represents the intentional absence of any object value.在 JavaScript 中,值null表示有意缺少任何 object 值。 null expresses a lack of identification, indicating that a variable points to no object. null表示缺少标识,表示一个变量指向没有object。

The global undefined property represents the primitive value undefined .全局undefined属性表示原始值undefined undefined is a primitive value automatically assigned to variables. undefined是自动分配给变量的原始值。 undefined is meant to say that the reference is not existing. undefined表示引用不存在。

I completely disagree that usage null or undefined is unnecessary.我完全不同意使用 null 或 undefined 是不必要的。 undefined is thing which keeping alive whole prototype chaining process. undefined 是使整个原型链接过程保持活力的东西。 So compiler only with null can't check if this property just equal to null, or its not defined in endpoint prototype.因此,仅使用 null 的编译器无法检查此属性是否等于 null,或者它未在端点原型中定义。 In other dynamic typed languages(fe Python) it throws exception if you want access to not defined property, but for prototype-based languages compiler should also check parent prototypes and here are the place when undefined need most.在其他动态类型语言(fe Python)中,如果你想访问未定义的属性,它会抛出异常,但对于基于原型的语言,编译器还应该检查父原型,这是最需要未定义的地方。

Whole meaning of using null is just bind variable or property with object which is singleton and have meaning of emptiness,and also null usage have performance purposes. Whole meaning of using null is just bind variable or property with object which is singleton and have meaning of emptiness,and also null usage have performance purposes. This 2 code have difference execution time.这两个代码有不同的执行时间。

var p1 = function(){this.value = 1};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
    p = new p1();
    if(index > 50000000){
       p.x = "some_string";
    }

    return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)

var p2 = function(){this.value = 1, p.x = null};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
    p = new p2();
    if(index > 50000000){
       p.x = "some_string";
    }

    return p; 
});
big_array.reduce((sum, p)=> sum + p.value, 0)

I'm working through this exact question right now, and looking at the following philosophy:我现在正在解决这个确切的问题,并研究以下理念:

  1. Any function that is intended to return a result should return null if it fails to find a result任何旨在返回结果的 function 如果找不到结果,则应返回 null
  2. Any function that is NOT intended to return a result implicitly returns undefined.任何不打算返回结果的 function 都会隐式返回 undefined。

For me, this question is significant because anyone calling a function that returns a result should have no question as to whether to test for undefined vs null.对我来说,这个问题很重要,因为任何调用返回结果的 function 的人都应该毫无疑问是否测试未定义与 null。

This answer does not attempt to address:此答案不尝试解决:

  1. Property values of null vs undefined null 与未定义的属性值
  2. Variables within your functions being null vs undefined函数中的变量是 null 与未定义

In my opinion, variables are your own business and not a part of your API, and properties in any OO system are defined and therefore should be defined with value different from what they would be if not defined (null for defined, undefined is what you get when accessing something that is not in your object).在我看来,变量是您自己的事情,而不是您的 API 的一部分,并且任何 OO 系统中的属性都已定义,因此应使用与未定义时不同的值定义(null 表示已定义,未定义是您的get 访问不在您的对象中的东西)。

Here's a reason: var undefined = 1 is legal javascript, but var null = 1 is a syntax error.这是一个原因: var undefined = 1是合法的 javascript,但var null = 1是语法错误。 The difference is that null is a language keyword, while undefined is, for some reason, not.不同之处在于null是语言关键字,而undefined由于某种原因不是。

If your code relies on comparisons to undefined as if it's a keyword ( if (foo == undefined) -- a very easy mistake to make) that only works because nobody has defined a variable with that name.如果您的代码依赖于与undefined的比较,就好像它是一个关键字( if (foo == undefined) - 一个非常容易犯的错误),它只会起作用,因为没有人使用该名称定义变量。 All that code is vulnerable to someone accidentally or maliciously defining a global variable with that name.所有这些代码都容易受到意外或恶意使用该名称定义全局变量的人的攻击。 Of course, we all know that accidentally defining a global variable is totally impossible in javascript...当然,我们都知道在javascript中意外定义一个全局变量是完全不可能的……

Just wanna add that with usage of certain javascript libraries, null and undefined can have unintended consequences.只是想补充一点,使用某些 javascript 库,null 和 undefined 可能会产生意想不到的后果。

For example, lodash's get function, which accepts a default value as a 3rd argument:例如,lodash 的get function,它接受一个默认值作为第三个参数:

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 .另一个例子:如果你在 React 中使用 defaultProps,如果传递了一个属性null ,则不会使用默认道具,因为null 被解释为定义的值 eg例如

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"

Unknown variable: undefined .未知变量: undefined

Known variable yet no value: null .已知变量但没有值: null

  1. You receive an object from a server, server_object .您从服务器server_object收到 object 。
  2. You reference server_object.errj .您引用server_object.errj It tells you it's undefined .它告诉你它是undefined That means it doesn't know what that is.这意味着它不知道那是什么。
  3. Now you reference server_object.err .现在您引用server_object.err It tells you it's null .它告诉你它是null That means you're referencing a correct variable but it's empty;这意味着您引用了一个正确的变量,但它是空的; therefore no error.因此没有错误。

The problem is when you declare a variable name without a value ( var hello ) js declares that as undefined : this variable doesn't exist;问题是当你声明一个没有值的变量名( var hello )时,js 将其声明为undefined :这个变量不存在; whereas programmers mostly mean: “I've not given it a value yet”, the definition of null .而程序员的主要意思是:“我还没有给它一个值”, null的定义。

So the default behavior of a programmer—declaring a variable without a value as nothing—is at odds with js—declaring it as not existing.因此,程序员的默认行为——将没有值的变量声明为空——与 js 不一致——将其声明为不存在。 And besides, !undefined and !null are both true so most programmers treat them as equivalent.此外, !undefined!null都是true ,所以大多数程序员将它们视为等价的。

You could of course ensure you always do var hello = null but most won't litter their code as such to ensure type sanity in a deliberately loosely-typed language, when they and the !你当然可以确保你总是做var hello = null但大多数人不会乱扔他们的代码以确保在故意松散类型的语言中类型健全,当他们和! operator treat both undefined and null as equivalent.运算符将undefinednull视为等效。

There are already some good answers here but not the one that I was looking for.这里已经有一些很好的答案,但不是我想要的。 null and undefined both "technically" do the same thing in terms of both being falsy, but when I read through code and I see a "null" then I'm expecting that it's a user defined null, something was explicitly set to contain no value, if I read through code and see "undefined" then I assume that it's code that was never initialized or assigned by anything. nullundefined两者“在技术上”都在虚假方面做同样的事情,但是当我阅读代码并看到一个“null”时,我期待它是用户定义的 null,某些东西被明确设置为包含 no值,如果我通读代码并看到“未定义”,那么我假设它是从未被任何东西初始化或分配的代码。 In this way code can communicate to you whether something was caused by uninitialized stuff or null values.通过这种方式,代码可以与您沟通是否是由未初始化的东西或 null 值引起的。 Because of that you really shouldn't assign "undefined" manually to something otherwise it messes with the way you (or another developer) can read code.因此,您真的不应该手动将“未定义”分配给某些东西,否则它会干扰您(或其他开发人员)阅读代码的方式。 If another developer sees "undefined" they're not going to intuitively assume it's you who made it undefined, they're going to assume it's not been initialized when in fact it was.如果另一个开发人员看到“未定义”,他们不会直观地认为是您将其设置为未定义,他们会认为它没有被初始化,而实际上它是。 For me this is the biggest deal, when I read code I want to see what it's telling me, I don't want to guess and figure out if stuff has "actually" been initialized.对我来说,这是最大的问题,当我阅读代码时,我想看看它告诉我什么,我不想猜测和弄清楚东西是否“实际上”被初始化了。

Not even to mention that using them in typescript means two different things.更不用说在 typescript 中使用它们意味着两件不同的事情。 Using:使用:

interface Example {
    name?: string
}

Means that name can be undefined or a string, but it can't be null.表示名称可以是未定义的或字符串,但不能是 null。 If you want it null you have to explicitly use:如果你想要它 null 你必须明确使用:

interface Example {
  name: string | null
}

And even then you'll be forced to initialize it at least with "null".即使这样,您也将被迫至少使用“null”对其进行初始化。

That's of course only true if you're using "strictNullChecks": true in tsconfig.json .当然,只有在tsconfig.json中使用"strictNullChecks": true

Based on a recent breakage we ran into, the example below shows why I prefer to use undefined over null , unless there is a specific reason to do otherwise:根据我们最近遇到的一个问题,下面的示例说明了为什么我更喜欢使用undefined而不是null ,除非有特定的理由不这样做:

function myfunc (myArg) {
    if (typeof myArg === 'string') {
        console.log('a', myArg);
    } else if (typeof abc === 'object') {
        console.log('b', myArg);
        if (myArg.id) {
           console.log('myArg has an id');
        } else {
           console.log('myArg has an id');
        }
    } else {
        console.log('no value');
    }
}

The following values will play nicely:以下值将很好地发挥作用:

'abc'
{}
undefined
{ id: 'xyz' }

On the other hand the assumption of null and undefined being equivalent here breaks the code.另一方面,假设nullundefined在这里是等价的会破坏代码。 The reason being is that null is of type of object , where as undefined is of type undefined .原因是null属于object类型,其中undefined属于undefined类型。 So here the code breaks because you can't test for a member on null .因此,这里的代码中断了,因为您无法在null上测试成员。

I have seen a large number of cases with code of similar appearance, where null is just asking for problems:我见过大量代码外观相似的案例,其中null只是在问问题:

if (typeof myvar === 'string') {
  console.log(myvar);
} else if (typeof myvar === 'object') {
  console.log(myvar.id);  
}

The fix here would be to explicitly test for null:此处的解决方法是显式测试 null:

if (typeof myvar === 'string') {
  console.log(myvar);
} else if (myvar !== null && typeof myvar === 'object') {
  console.log(myvar.id);  
}

My attitude is to code for the weaknesses of a language and the typical behaviours of programmers of that language, hence the philosophy here of going with 'undefined' bey default.我的态度是针对一种语言的弱点和该语言程序员的典型行为进行编码,因此这里的哲学是默认使用“未定义”。

To write simple code you need to keep complexity and variation down.要编写简单的代码,您需要降低复杂性和变化。 When a variable or a property on an object does not have a value it is undefined, and for a value to be null you need to assign it a null value.当 object 上的变量或属性没有值时,它是未定义的,并且要为 null 分配一个 null 值。

Undeclared vs Null未声明与 Null

null is both an Object "type" and one of the 7 unique primitive value types called null null既是Object “类型”,又是称为null的 7 个唯一原始值类型之一

undefined is both a global scope property called undefined (window.undefined) and one of the 7 unique primitive value types called undefined undefined既是称为undefined (window.undefined) 的全局 scope 属性,也是称为undefined的 7 个唯一原始值类型之一

It is the primitive types we use as values we are interested in.它是我们用作我们感兴趣的值的原始类型

In the case of null , as a value type it means an empty value has been assigned to a variable.null的情况下,作为值类型,这意味着已将空值分配给变量。 It may mean a variable has an empty value but it is still a value.这可能意味着一个变量有一个空值,但它仍然是一个值。 It also initializes the variable so it exists, and is not undefined .它还初始化变量,使其存在,而不是undefined

undefined is a special case. undefined是一个特例。 When you create a variable it is assigned undefined by default prior to assigning a value, and implies the variable does not exist or exists but has no value assigned.当您创建一个变量时,默认情况下它在赋值之前被赋值为undefined ,这意味着该变量不存在或存在但没有赋值。 Like null it is also a primitive value type .null一样,它也是原始值类型 But unlike null it means the variable does not exist.但与null不同,这意味着该变量不存在。 That is why its always better to check if the variable exists and has been assigned a variable using undefined before checking if the value is null or empty.这就是为什么在检查值是null还是空之前,最好先检查变量是否存在并使用 undefined 分配了一个变量。 undefined implies no variable or object exists in the compilation. undefined表示编译中没有变量或 object 存在。 The variable has either not been declared or declared with a missing value so not initialized .该变量要么没有被声明,要么被声明为缺少值,因此没有被初始化 So undefined is a very good way to avoid many types of errors and supersedes null .所以undefined是避免许多类型错误并取代null的好方法。

That is why I would not rely on "truthy" checks for true/false with null and undefined , even though they will return a false response, as undefined implies a missing feature, object, or variable, not just a true/false check.这就是为什么我不会依赖nullundefined的“真实”检查真/假,即使它们会返回错误响应,因为undefined意味着缺少功能、object 或变量,而不仅仅是真/假检查。 It implies something more.它暗示了更多的东西。

Let's look at undefined first:我们先来看undefined的:

        //var check1;// variable doesnt even exist so not assigned to "undefined"
        var check2;// variable declared but not initialized so assigned "undefined"
        var check3 = 'hello world';// variable has a value so not undefined

        console.log('What is undefined?');

        //console.log(check1 === undefined);// ERROR! check1 does not exist yet so not assigned undefined!
        console.log(check2 === undefined);// True
        console.log(check3 === undefined);// False
        console.log(typeof check1 === 'undefined');// True
        console.log(typeof check2 === 'undefined');// True
        console.log(typeof check3 === 'undefined');// False

As you can see undeclared variables, or declared but not initialized , both are assigned a type of undefined .如您所见,未声明的变量或已声明但未初始化的变量都被分配了一种undefined的类型。 Notice declared variables that are not initialized are assigned a value of undefined , the primitive value type but variables that do not exist are undefined types .请注意,未初始化的声明变量被分配一个undefined的值,原始值类型但不存在的变量是未定义类型

null has nothing to do with missing variables or variables not yet assigned values, as null is still a value. null与缺少变量或尚未赋值的变量无关,因为null仍然是一个值。 So anything with a null is already declared and initialized .所以任何带有null的东西都已经被声明初始化了。 Also notice a variable assigned a null value is actually an object type unlike undefined types .另请注意,与未定义类型不同,分配了null值的变量实际上是object类型。 For example...例如...

        var check4 = null;
        var check5 = 'hello world';

        console.log('What is null?');

        console.log(check4 === undefined);// False
        console.log(check5 === undefined);// False
        console.log(typeof check4 === 'undefined');// False
        console.log(typeof check5 === 'undefined');// False
        console.log(typeof check4);// return 'object'
        console.log(typeof check5);// return 'string'

As you can see each act differently and yet both are primitive values you can assign any variable.正如您所看到的,每种行为都不同,但两者都是原始值,您可以分配任何变量。 Just understand they represent different states of variables and objects.只需了解它们代表变量和对象的不同状态即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM