tes*_*dtv 115 javascript null undefined
我很困惑JavaScript何时返回null
或undefined
.不同的浏览器似乎也以不同的方式返回这些.
您能否举例说明null
/ undefined
返回它们的浏览器.
虽然我现在对这undefined
方面很清楚,但我仍然没有100%明确表示null
.它是否类似于空白值?
例如,您有一个没有设置任何值的文本框.现在,当您尝试访问其值时,它会是null
或者undefined
它们是否相似?
Cor*_*oss 122
我发现其中一些答案是模糊和复杂的,我发现找出这些东西的最佳方法是打开控制台并自己测试.
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
Run Code Online (Sandbox Code Playgroud)
所以这绝对是JavaScript中微妙的细微差别之一.正如您所看到的,您可以覆盖它的值undefined
,使其与之相比有些不可靠null
.据我所知==
,使用操作员可以可靠地使用null
和undefined
互换.但是,由于null
无法重新定义的优点,我可能会在使用时使用它==
.
例如,variable != null
将永远如果返回false variable
等于任一null
或undefined
,而variable != undefined
将返回假,如果variable
等于或者null
或undefined
除非undefined
预先重新分配.
您可以可靠地使用===
运算符来区分undefined
和null
,如果您需要确保值实际undefined
(而不是null
).
Null
和Undefined
两个内置的类型六.4.3.9未定义的值
未赋值变量时使用的原始值
4.3.11空值
原始值,表示故意缺少任何对象值
ken*_*bec 80
的DOM方法getElementById()
,nextSibling()
,childNodes[n]
,parentNode()
等等返回null
(定义但不具有值),当该呼叫不返回节点对象.
该属性的定义,但对象是指不存在.
这是为数不多的几次你可能不希望测试equality-
if(x!==undefined)
对于null值将为true
但if(x!= undefined)
将是真实的(只)对于那些也不值undefined
或null
.
Bjo*_*orn 50
您未定义各种方案:
您使用var声明变量但从未设置它.
var foo;
alert(foo); //undefined.
Run Code Online (Sandbox Code Playgroud)
您尝试访问您从未设置的对象上的属性.
var foo = {};
alert(foo.bar); //undefined
Run Code Online (Sandbox Code Playgroud)
您尝试访问从未提供的参数.
function myFunction (foo) {
alert(foo); //undefined.
}
Run Code Online (Sandbox Code Playgroud)
正如cwolves在另一个答案的评论中指出的那样,函数没有返回值.
function myFunction () {
}
alert(myFunction());//undefined
Run Code Online (Sandbox Code Playgroud)
通常必须在变量或属性上有意设置null(请参阅注释,以便在未设置的情况下显示).另外,null是类型object
,undefined是类型undefined
.
我还应该注意,null在JSON中是有效的,但未定义的不是:
JSON.parse(undefined); //syntax error
JSON.parse(null); //null
Run Code Online (Sandbox Code Playgroud)
我可能会遗漏一些东西,但是afaik,你undefined
只会得到
更新:好的,我错过了很多,试图完成:
你得到undefined
......
...当您尝试访问不存在的对象的属性时:
var a = {}
a.foo // undefined
Run Code Online (Sandbox Code Playgroud)
...当你声明了一个变量但没有初始化它时:
var a;
// a is undefined
Run Code Online (Sandbox Code Playgroud)
...当您访问没有传递值的参数时:
function foo (a, b) {
// something
}
foo(42); // b inside foo is undefined
Run Code Online (Sandbox Code Playgroud)
...当函数没有返回值时:
function foo() {};
var a = foo(); // a is undefined
Run Code Online (Sandbox Code Playgroud)
可能是某些内置函数会返回null
一些错误,但如果是这样,那么就会记录下来.null
是JavaScript的具体价值,undefined
不是.
通常你不需要区分它们.根据变量的可能值,if(variable)
用于测试是否设置了值(两者都是,null
并且undefined
评估为false
)就足够了.
不同的浏览器似乎也以不同的方式返回这些.
请举一个具体的例子.
归档时间: |
|
查看次数: |
110687 次 |
最近记录: |