Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 将变量设置为未定义且为空_Jquery_Variables - Fatal编程技术网

Jquery 将变量设置为未定义且为空

Jquery 将变量设置为未定义且为空,jquery,variables,Jquery,Variables,我刚读了一些代码,我看到这一行: var foo = null, undefined; 当我测试变量时,它既是空的,也是未定义的 因此,我的问题是,设置空变量和未定义变量的目的是什么? 我不明白。 感谢您的解释。如评论中所述,您可能没有以正确的方式测试foo,变量不能同时为未定义的和空 var foo = null, undefined; alert(foo); //shows null alert(typeof foo); //shows object (not undefined) 发生

我刚读了一些代码,我看到这一行:

var foo = null, undefined;
当我测试变量时,它既是空的,也是未定义的

因此,我的问题是,设置空变量和未定义变量的目的是什么? 我不明白。
感谢您的解释。

如评论中所述,您可能没有以正确的方式测试foo,变量不能同时为未定义的

var foo = null, undefined;
alert(foo); //shows null
alert(typeof foo); //shows object (not undefined)
发生了什么事?逗号表示您正在声明一个附加变量。由于undefined已经是一个关键字,所以语句的这一特定部分没有任何效果。但是,如果您这样做:

var foo = null, undefined1;
alert(foo); //shows null
alert(typeof foo); //shows object (not undefined)
alert(undefined1); //shows undefined
alert(typeof undefined1); //shows undefined

您可以看到,您实际上是在声明一个没有初始值的新变量,
undefined1

该语句的目的是在具有相同名称的变量中有一个的局部声明

例如:

// declare two local variables
var foo = null, undefined;

console.log(foo === undefined); // false
它类似于:

function test(foo, undefined)
{
    console.log(foo === undefined); // false
}
test(null); // only called with a single argument
这通常是不必要的,因为健全的浏览器不允许任何人重新定义
未定义的
的含义,并且会抱怨:

保留名称“未定义”

基本上,我建议不要这样做:

var foo = null;
顺便说一句,上述声明不应与以这种方式使用相混淆:

var foo;

foo = 1, 2;
console.log(foo); // 2
肖特:那没用

如果不指定任何内容,则变量
未定义
。您可以分配
null
使其为null。然而,你的比较也很重要

现在,严格比较具有
===

if(foo === null) //false............can be true if assigned to null
    alert('3');
if(foo === undefined) //true.......can be flase if assigned to null
    alert('4');

foo
变量将是
null
undefined
在上述语句中是无用的,因此,此声明会产生死代码?在检查undefined时要小心,使用===或typeof如何检查变量它是null和undefined?
if(foo === null) //false............can be true if assigned to null
    alert('3');
if(foo === undefined) //true.......can be flase if assigned to null
    alert('4');