我对 JavaScript 何时返回感到困惑null
or undefined
。此外,不同的浏览器似乎以不同的方式返回这些内容。
我正在寻找一些例子null
/undefined
与返回它们的浏览器。
虽然我现在很清楚undefined
方面,我还不是100%清楚null
。它类似于空白值吗?
例如。您有一个未设置任何值的文本框。现在当你尝试访问它的值时,它会是null
or undefined
它们相似吗?
我发现其中一些答案模糊且复杂,我发现确定这些问题的最佳方法就是打开控制台并亲自测试。
var x;
x == null // true
x == undefined // true
x === null // false
x === undefined // true
var y = null;
y == null // true
y == undefined // true
y === null // true
y === undefined // false
typeof x // 'undefined'
typeof y // 'object'
var z = {abc: null};
z.abc == null // true
z.abc == undefined // true
z.abc === null // true
z.abc === undefined // false
z.xyz == null // true
z.xyz == undefined // true
z.xyz === null // false
z.xyz === undefined // true
null = 1; // throws error: invalid left hand assignment
undefined = 1; // works fine: this can cause some problems
所以这绝对是 JavaScript 更微妙的细微差别之一。如您所见,您可以覆盖undefined
,与null
。使用==
操作员,您可以可靠地使用null
and undefined
据我所知可以互换。然而,由于这样的优势,null
无法重新定义,我可能会在使用时使用它==
.
例如,variable != null
总是返回 false 如果variable
等于null
or undefined
, 然而variable != undefined
将返回 false 如果variable
等于null
or undefined
UNLESS undefined
被提前重新分配。
您可以可靠地使用===
运算符来区分undefined
and null
,如果您需要确保某个值实际上是undefined
(而不是null
).
根据 ECMAScript 5 规范:
- Both
Null
and Undefined
是六种内置类型中的两种。
4.3.9 未定义值
当变量尚未赋值时使用的原始值
4.3.11 空值
表示有意不存在任何对象值的原始值
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)