Javascript 如果语句运行在false上?
使用javascript 我有一个函数Javascript 如果语句运行在false上?,javascript,Javascript,使用javascript 我有一个函数 function test(variable) { if(variable != 'undefined') { console.log('variable is not set'); console.log('variable', where); } } 我使用test()调用它 然而在控制台里我得到了 “何处未设置” '其中设置为未定义' 为什么? 更新 这个函数不是我实际使用的 如果变量未定义,则函数不应执行任何操作
function test(variable)
{
if(variable != 'undefined')
{
console.log('variable is not set');
console.log('variable', where);
}
}
我使用test()调用它代码>
然而在控制台里我得到了
“何处未设置”
'其中设置为未定义'
为什么?
更新
这个函数不是我实际使用的
如果变量未定义,则函数不应执行任何操作
该示例显示if语句不起作用
但问题实际上是我在使用ifvariable!='未定义“
而不是变量!=未定义的
您在同一个分支中有两个控制台。log
调用。改为这样做:
function test(variable)
{
if(variable != 'undefined')
{
console.log('where is not set');
}
else
{
console.log('where is set as ', where);
}
}
除此之外:如果要测试变量是否未定义,请使用测试类型:typeof variable!='未定义的“
。当前,您只需测试变量
是否不等于字符串值“未定义”
您正在测试变量
的字符串内容是否为“未定义”
你可能想要的是
if(typeof variable != 'undefined')
函数的其余部分对我来说也没有意义。Where
来自哪里?我不太理解您的问题,但请尝试使用不同的参数名称,而不是“变量”。看看错误是否还在那里
加上如下调用函数:test(parametervaluehere)
最好的