Javascript 检查函数内部的null值会返回错误的结果

Javascript 检查函数内部的null值会返回错误的结果,javascript,if-statement,null,Javascript,If Statement,Null,我不知道这里发生了什么事。当我检查函数中的变量是否为null时,我得到的(变量不为null)是不正确的,但如果我删除函数部分并直接测试它,它将返回正确的(变量为null)。发生了什么事?为什么javascript如此混乱 var variable = null; function scoppedVariables(variable) { if( variable === null ) { console.log('variable is null'); } else { conso

我不知道这里发生了什么事。当我检查函数中的变量是否为null时,我得到的(变量不为null)是不正确的,但如果我删除函数部分并直接测试它,它将返回正确的(变量为null)。发生了什么事?为什么javascript如此混乱

var variable = null;

function scoppedVariables(variable) {
  if( variable === null ) {
  console.log('variable is null');
} else {
  console.log('variable is not null');
}

}

scoppedVariables();

由于您接受
变量
作为参数,因此它将接管您在函数外部定义的
变量
。由于没有在函数调用中传递它,因此在函数中它是
未定义的
,而不是
null
。(您可以使用非严格比较,但在本例中,您无法计算实际发生的情况;)

调用该方法时没有参数,因此
变量
未定义,严格来说,它不等于
null

使用参数调用函数或将其从签名中删除:

function scoppedVariables(){..}

当以这种方式调用时,它将访问全局参数,但最好将您想要的变量传递给函数。

修改您的函数以使用此参数

if (typeof variable == 'undefined') {
    console.log('variable is undefined');
} else {
    console.log('variable is defined');
    if (variable == null) {
        console.log('variable is null);
    } else {
        console.log('variable is not null');
    }
}

您没有在函数调用中传递任何内容,因此
variable
将是未定义的,而不是null。您可能希望在参数输入方面更具防御性,正如我在这里所说明的。

scoppedVariables()在调用函数的位置传递值。您没有向函数传递任何内容,因此它没有任何可处理的内容,无论是null还是其他。我现在觉得很愚蠢:p
if (typeof variable == 'undefined') {
    console.log('variable is undefined');
} else {
    console.log('variable is defined');
    if (variable == null) {
        console.log('variable is null);
    } else {
        console.log('variable is not null');
    }
}