热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在JavaScript中什么时候使用null或未定义?(复制)-WhenisnullorundefinedusedinJavaScript?[duplicate]

Thisquestionalreadyhasananswerhere:这个问题已经有了答案:Whatisthedifferencebetweennull

This question already has an answer here:

这个问题已经有了答案:

  • What is the difference between null and undefined in Javascript? 30 answers
  • 在Javascript中,null和未定义的区别是什么?30的答案

I am really confused as to when Javascript returns null or undefined. Also different browsers seem to be returning these differently.

当Javascript返回null或未定义时,我真的很困惑。同样,不同的浏览器返回这些信息的方式也不同。

Could you please give some examples of null/undefined with the browsers that return them.

你能给我一些返回null/undefined的浏览器的例子吗?

While I am now clear on the undefined aspect, I am still not 100% clear on null. Is it similar to a blank value?

虽然我现在已经清楚了未定义的方面,但我仍然不是100%清楚null。它与空白值相似吗?

E.g. You have a text box which does not have any value set. Now when you try to access its value, will it be null or undefined and are they similar?

例如,你有一个没有任何值集的文本框,现在当你试图访问它的值时,它是null还是undefined,它们相似吗?

6 个解决方案

#1


79  

The DOM methods getElementById(), nextSibling(), childNodes[n], parentNode() and so on return null (defined but having no value) when the call does not return a node object.

DOM方法getElementById()、nextSibling()、childNodes[n]、parentNode()等在调用不返回节点对象时返回null(定义但没有值)。

The property is defined, but the object it refers to does not exist.

属性被定义,但是它引用的对象不存在。

This is one of the few times you may not want to test for equality-

这是少数几次你可能不想测试平等-

if(x!==undefined) will be true for a null value

对于空值,if(x!= undefined)为真

but if(x!= undefined) will be true (only) for values that are not either undefined or null.

但如果(x != undefined)将对非无定义或null的值为true。

#2


118  

I find that some of these answers are vague and complicated, I find the best way to figure out these things for sure is to just open up the console and test it yourself.

我发现其中的一些答案是模糊的和复杂的,我发现确定这些事情的最好方法是打开控制台并自己测试它。

var x;x == null            // truex == undefined       // truex === null           // falsex === undefined      // truevar y = null;y == null            // truey == undefined       // truey === null           // truey === undefined      // falsetypeof x             // 'undefined'typeof y             // 'object'var z = {abc: null};z.abc == null        // truez.abc == undefined   // truez.abc === null       // truez.abc === undefined  // falsez.xyz == null        // truez.xyz == undefined   // truez.xyz === null       // falsez.xyz === undefined  // truenull = 1;            // throws error: invalid left hand assignmentundefined = 1;       // works fine: this can cause some problems

So this is definitely one of the more subtle nuances of Javascript. As you can see, you can override the value of undefined, making it somewhat unreliable compared to null. Using the == operator, you can reliably use null and undefined interchangeably as far as I can tell. However, because of the advantage that null cannot be redefined, I might would use it when using ==.

因此,这绝对是Javascript更微妙的细微差别之一。如您所见,您可以重写undefined的值,使它与null相比有些不可靠。使用==运算符,就我所知,您可以可靠地使用null和undefined作为交换。但是,由于null不能重新定义的优点,我可能在使用==时使用它。

For example, variable != null will ALWAYS return false if variable is equal to either null or undefined, whereas variable != undefined will return false if variable is equal to either null or undefined UNLESS undefined is reassigned beforehand.

例如,如果变量= null或undefined,则变量!= null将返回false,而如果变量= null或undefined则返回false,除非事先重新分配undefined。

You can reliably use the === operator to differentiate between undefined and null, if you need to make sure that a value is actually undefined (rather than null).

如果您需要确保一个值实际上是未定义的(而不是null),您可以可靠地使用=== =运算符来区分未定义和null。

According to the ECMAScript 5 spec:

  • Both Null and Undefined are two of the six built in types.
  • Null和Undefined都是构建在类型中的六个类型中的两个。

4.3.9 undefined value

4.3.9未定义的值

primitive value used when a variable has not been assigned a value

当变量未被赋值时使用的原始值

4.3.11 null value

4.3.11空值

primitive value that represents the intentional absence of any object value

表示有意没有任何对象值的原始值。

#3


49  

You get undefined for the various scenarios:

对于各种场景,你没有定义:

You declare a variable with var but never set it.

使用var声明一个变量,但从不设置它。

var foo; alert(foo); //undefined.

You attempt to access a property on an object you've never set.

您试图访问从未设置的对象上的属性。

var foo = {};alert(foo.bar); //undefined

You attempt to access an argument that was never provided.

您试图访问一个从未提供的参数。

function myFunction (foo) {  alert(foo); //undefined.}

As cwolves pointed out in a comment on another answer, functions that don't return a value.

正如cwolf在另一个答案的评论中指出的,函数不返回值。

function myFunction () {}alert(myFunction());//undefined

A null usually has to be intentionally set on a variable or property (see comments for a case in which it can appear without having been set). In addition a null is of type object and undefined is of type undefined.

通常必须在变量或属性上故意设置null(在没有设置的情况下可以出现,请参阅注释)。另外,一个null类型的对象和未定义的类型是未定义的。

I should also note that null is valid in JSON but undefined is not:

我还要注意,null在JSON中是有效的,但未定义的不是:

JSON.parse(undefined); //syntax errorJSON.parse(null); //null

#4


9  

I might be missing something, but afaik, you get undefined only

我可能漏掉了一些东西,但是,你只能得到不确定的结果

Update: Ok, I missed a lot, trying to complete:

更新:好的,我错过了很多,试图完成:

You get undefined...

你未定义……

... when you try to access properties of an object that don't exist:

…当您试图访问一个不存在的对象的属性时:

var a = {}a.foo // undefined

... when you have declared a variable but not initialized it:

…当您声明了一个变量但没有初始化它时:

var a;// a is undefined

... when you access a parameter for which no value was passed:

…当您访问一个没有传递值的参数时:

function foo (a, b) {    // something}foo(42); // b inside foo is undefined

... when a function does not return a value:

…当一个函数不返回值时:

function foo() {};var a = foo(); // a is undefined

It might be that some built-in functions return null on some error, but if so, then it is documented. null is a concrete value in Javascript, undefined is not.

一些内置函数可能会在某些错误上返回null,但如果是,则会对其进行文档化。null是Javascript中的一个具体值,未定义的则不是。


Normally you don't need to distinguish between those. Depending on the possible values of a variable, it is sufficient to use if(variable) to test whether a value is set or not (both, null and undefined evaluate to false).

通常你不需要区分它们。根据变量的可能值,使用if(变量)来测试是否设置了一个值就足够了(null和undefined evaluate to false)。

Also different browsers seem to be returning these differently.

同样,不同的浏览器返回这些信息的方式也不同。

Please give a concrete example.

请给出一个具体的例子。

#5


3  

Regarding this topic the specification (ecma-262) is quite clear

关于这个主题,规范(ecma-262)非常清楚

I found it really useful and straightforward, so that I share it:- Here you will find Equality algorithm- Here you will find Strict equality algorithm

我发现它非常有用和简单,所以我分享它:-在这里你会发现平等算法-在这里你会发现严格的平等算法。

I bumped into it reading "Abstract equality, strict equality, and same value" from mozilla developer site, section sameness.

我从mozilla开发者网站“相似度”中偶然发现了“抽象的平等、严格的平等和相同的价值”。

I hope you find it useful.

我希望你觉得它有用。

#6


0  

A property, when it has no definition, is undefined. null is an object. It's type is null. undefined is not an object, its type is undefined.

没有定义的属性是未定义的。零是一个对象。它的类型为空。undefined不是对象,它的类型是undefined。

This is a good article explaining the difference and also giving some examples.

这是一篇很好的文章,解释了其中的差异,并给出了一些例子。

null vs undefined

零和未定义的


推荐阅读
  • Hibernate延迟加载深入分析-集合属性的延迟加载策略
    本文深入分析了Hibernate延迟加载的机制,特别是集合属性的延迟加载策略。通过延迟加载,可以降低系统的内存开销,提高Hibernate的运行性能。对于集合属性,推荐使用延迟加载策略,即在系统需要使用集合属性时才从数据库装载关联的数据,避免一次加载所有集合属性导致性能下降。 ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • IjustinheritedsomewebpageswhichusesMooTools.IneverusedMooTools.NowIneedtoaddsomef ... [详细]
  • 本文介绍了在wepy中运用小顺序页面受权的计划,包含了用户点击作废后的从新受权计划。 ... [详细]
  • 模板引擎StringTemplate的使用方法和特点
    本文介绍了模板引擎StringTemplate的使用方法和特点,包括强制Model和View的分离、Lazy-Evaluation、Recursive enable等。同时,还介绍了StringTemplate语法中的属性和普通字符的使用方法,并提供了向模板填充属性的示例代码。 ... [详细]
  • 本文讨论了编写可保护的代码的重要性,包括提高代码的可读性、可调试性和直观性。同时介绍了优化代码的方法,如代码格式化、解释函数和提炼函数等。还提到了一些常见的坏代码味道,如不规范的命名、重复代码、过长的函数和参数列表等。最后,介绍了如何处理数据泥团和进行函数重构,以提高代码质量和可维护性。 ... [详细]
  • Android实战——jsoup实现网络爬虫,糗事百科项目的起步
    本文介绍了Android实战中使用jsoup实现网络爬虫的方法,以糗事百科项目为例。对于初学者来说,数据源的缺乏是做项目的最大烦恼之一。本文讲述了如何使用网络爬虫获取数据,并以糗事百科作为练手项目。同时,提到了使用jsoup需要结合前端基础知识,以及如果学过JS的话可以更轻松地使用该框架。 ... [详细]
  • 本文介绍了2015年九月八日的js学习总结及相关知识点,包括参考书《javaScript Dom编程的艺术》、js简史、Dom、DHTML、解释型程序设计和编译型程序设计等内容。同时还提到了最佳实践是将标签放到HTML文档的最后,并且对语句和注释的使用进行了说明。 ... [详细]
  • 本文总结了在编写JS代码时,不同浏览器间的兼容性差异,并提供了相应的解决方法。其中包括阻止默认事件的代码示例和猎取兄弟节点的函数。这些方法可以帮助开发者在不同浏览器上实现一致的功能。 ... [详细]
  • 本文整理了Java中org.gwtbootstrap3.client.ui.Icon.addDomHandler()方法的一些代码示例,展示了Icon.ad ... [详细]
  • 本文介绍了闭包的定义和运转机制,重点解释了闭包如何能够接触外部函数的作用域中的变量。通过词法作用域的查找规则,闭包可以访问外部函数的作用域。同时还提到了闭包的作用和影响。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • 开发笔记:实验7的文件读写操作
    本文介绍了使用C++的ofstream和ifstream类进行文件读写操作的方法,包括创建文件、写入文件和读取文件的过程。同时还介绍了如何判断文件是否成功打开和关闭文件的方法。通过本文的学习,读者可以了解如何在C++中进行文件读写操作。 ... [详细]
  • 本文讨论了如何使用IF函数从基于有限输入列表的有限输出列表中获取输出,并提出了是否有更快/更有效的执行代码的方法。作者希望了解是否有办法缩短代码,并从自我开发的角度来看是否有更好的方法。提供的代码可以按原样工作,但作者想知道是否有更好的方法来执行这样的任务。 ... [详细]
author-avatar
孽尐星_186
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有