2010-09-01 44 views
0

使用JavaScript如果语句在false上运行?

我使用test();

但在控制台中我得到 “其中没有设置” 功能

function test(variable) 
{ 
    if(variable != 'undefined') 
    { 
    console.log('variable is not set'); 
    console.log('variable', where); 
    } 
} 

我把它叫做“其中被设置为未定义”

为什么?


更新 这个函数不是我实际使用的。

如果变量未定义,该函数不应该做任何事情。

该示例显示if语句不起作用。

但是这个问题实际上我如果variable != 'undefined'代替variable != undefined

回答

4

您正在测试variable是否有字符串内容"undefined"

你可能想要的是

if(typeof variable != 'undefined') 

功能的其余部分不做意义,我还没有,要么。 where从哪里来?

6

您在同一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'

-1

我不太理解你的问题,但尝试使用不同的参数名称而不是“变量”。看看错误是否仍然存在。

Plus调用如下函数:test(paramterValueHere);

最好

-1

试试这个;

if(variable !== 'undefined')