繁体   English   中英

JS:如何防止让双重声明? /确定是否定义了变量

[英]JS: How to prevent let double declaration? / determine if let variable is defined

如果我打开JS控制台并写:

let foo;

之后:

let foo = "bar"

控制台告诉我(正确)

Uncaught SyntaxError: Identifier 'foo' has already been declared

现在......有时我需要在现有脚本中注入我的代码,而我没有工具来确定是否已经定义了let变量。

我尝试使用此代码,但JS范围和逻辑存在明显问题....(注释代码)

 let foo; // Gloabl variable empty declare in a code far, far away console.log(foo); // undefined console.log(typeof foo === "undefined"); // test that determinate if condition is true if(typeof foo === "undefined"){ let foo = "test"; console.log(foo); // return "test" this means that foo as a local scope only inside this if... } console.log(foo); // return undefined not test! // and .. if I try to double declaration... let foo = "bar"; //error! 

所以...我怎样才能防止双重“让”声明? /如何确定是否定义了let var(声明?)

PS与“var”一切正常!!!

您可以为脚本定义范围。 您仍然可以访问该范围内的外部变量。

 let toto = 42; let foo = "bar"; console.log(toto); //Some added script { let toto = "hello world !"; console.log(toto); console.log(foo); } //back to main script console.log(toto); 

您仍然可以使用try - catch以编程方式检查变量是否存在,但在try { } catch { }范围内声明变量可能非常棘手

 let existingVariable = "I'm alive !"; try { console.log("existingVariable exists and contains : " + existingVariable); console.log("UndeclaredVariable exists and contains : " + UndeclaredVariable); } catch (ex) { if (ex instanceof ReferenceError) { console.log("Not good but I caught exception : " + ex); } } console.log("Looks like my script didn't crash :)"); 

如果您不想创建新范围以确保现有脚本中不存在您的变量,那么...前缀为let r1sivar_userinput

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM