JavaScript 中何时使用 null 或 undefined? [英] When is null or undefined used in JavaScript?

查看:36
本文介绍了JavaScript 中何时使用 null 或 undefined?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑 JavaScript 何时返回 nullundefined.此外,不同的浏览器似乎以不同的方式返回这些.

您能否举一些 null/undefined 的示例以及返回它们的浏览器.

虽然我现在清楚 undefined 方面,但我仍然不是 100% 清楚 null.是否类似于空白值?

例如您有一个没有设置任何值的文本框.现在,当您尝试访问它的值时,它是 null 还是 undefined 并且它们是否相似?

解决方案

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

属性已定义,但它所指的对象不存在.

这是您可能不想想要测试相等性的少数几次之一-

if(x!==undefined) 为空值时为真

但是 if(x!= undefined) 将(仅)对于不是 undefinednull 的值为真.

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

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

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

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?

解决方案

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.

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

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

这篇关于JavaScript 中何时使用 null 或 undefined?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆