使用 JavaScript
我有一个函数
function test(variable)
{
if(variable != 'undefined')
{
console.log('variable is not set');
console.log('variable', where);
}
}
我使用test();
来调用它
但在控制台中我得到 '哪里没有设置' '其中设置为未定义'
为什么?
更新 这个功能不是我实际使用的。
如果变量未定义,函数不应执行任何操作。
该示例是为了显示 if 语句不起作用。
但问题实际上是我使用 if variable != 'undefined'
而不是 variable != undefined
最佳答案
您在同一个 if
分支中有两个 console.log
调用。改为这样做:
function test(variable)
{
if(variable != 'undefined')
{
console.log('where is not set');
}
else
{
console.log('where is set as ', where);
}
}
除此之外:如果您想测试变量是否未定义,请使用 typeof
operator测试类型:typeof variable!= 'undefined'
。目前,您只需测试 variable
是否不等于字符串值 'undefined'
。
关于javascript - if 语句运行在 false 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3617498/