Javascript 通过函数切换变量
这个问题很简单。我希望能够检测变量是否为false,并将其设置为true,通常称为toggle 这是:Javascript 通过函数切换变量,javascript,variables,toggle,Javascript,Variables,Toggle,这个问题很简单。我希望能够检测变量是否为false,并将其设置为true,通常称为toggle 这是: var hello = false function toggleSt(I, E) { if ((I == "activate") && (!E)) { E = !E alert("activated") } else if ((I == "disable") && (E))
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)
我将代码粘贴到JSFIDLE上
Hello仍然是假的。Felix是对的。尝试:
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)
调用函数时,将hello分配给新变量E。因此,在函数中,新参数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)
E
将不会引用hello
,它将只具有相同的值。更改E
不会更改hello
。但这是硬编码!有可能的替代方案吗?