2011-08-10 72 views
0

这个问题很简单。我希望能够检测变量是否为假,并将其设置为true,通常称为切换。切换变量槽功能

这里是:

var hello = false 

function toggleSt(I, E) 
{ 
    if ((I == "activate") && (!E)) 
    { 
      E = !E 
      alert("activated") 
    } 
    else if ((I == "disable") && (E)) 
    { 
       E = !E 
       alert("disabled") 
    } 
} 

toggleSt("activate", hello) 

alert(hello) 

我粘贴上的jsfiddle代码,

http://jsfiddle.net/kpDSr/

你好还是假的。

+1

'E'将**不是对'hello'的引用,它只会具有相同的值。改变'E'不会改变'hello'。 –

回答

1

菲利克斯是对的。尝试:

var hello = false 

function toggleSt(I) 
{ 
    if ((I == "activate") && (!hello)) 
    { 
      hello = !hello; 
      alert("activated") 
    } 
    else if ((I == "disable") && (hello)) 
    { 
       hello = !hello 
       alert("disabled") 
    } 
} 

toggleSt("activate"); 

alert(hello) 
+0

但是这是硬编码!任何可能的选择? – Implosions

0

当您调用该函数时,您可以为新的var E指定hello。所以在函数中你有新的参数E设置为true/false。调用不带参数的函数作为hello,并使用hello作为全局变量将按预期工作。

var hello = false 

function toggleSt(I) 
{ 
    if ((I == "activate") && (!hello)) 
    { 
      hello = !hello 
      alert("activated") 
    } 
    else if ((I == "disable") && (hello)) 
    { 
       hello = !hello 
       alert("disabled") 
    } 
} 

toggleSt("activate") 

alert(hello)