我需要声明一个局部变量并在if语句的条件下测试它.我希望能够这样做,但是我需要在没有全球范围的情况下这样做; 这可能吗?
notWorkingSofar('#element');
function notWorkingSofar(a) {
if(!(b=document.getElementById(a.slice(1)))){return b;}
else{return false;}
}
Run Code Online (Sandbox Code Playgroud)
我需要它基本上这样做; 但是这会产生SyntaxError.
notWorkingSofar('#element');
function notWorkingSofar(a) {
if(!(**var** b=document.getElementById(a.slice(1)))){return b;}
else{return false;}
}
Run Code Online (Sandbox Code Playgroud)
有没有其他方法来访问或设置局部变量,除了"var variable ="之外?也许是通过function.variable,类似于window.variable ......虽然不确定.
编辑:尝试在这些链中进行:(!!(b = document.getElementById(a.slice(1)))?b:[0,])
你根本不需要变量.你可以这样做:
function notWorkingSofar(a) {
return document.getElementById(a.slice(1)) || false;
}
Run Code Online (Sandbox Code Playgroud)
或者如果你不打算测试严格的平等,甚至
return document.getElementById(a.slice(1));
Run Code Online (Sandbox Code Playgroud)
会没事的.
如果你真的想要一个局部变量而不是声明它
var b;
Run Code Online (Sandbox Code Playgroud)
预先.