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

r1s*_*1si 6 javascript variables let ecmascript-6

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

let foo;
Run Code Online (Sandbox Code Playgroud)

之后:

let foo = "bar"
Run Code Online (Sandbox Code Playgroud)

控制台告诉我(正确)

Uncaught SyntaxError: Identifier 'foo' has already been declared
Run Code Online (Sandbox Code Playgroud)

现在......有时我需要在现有脚本中注入我的代码,而我没有工具来确定是否已经定义了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!
Run Code Online (Sandbox Code Playgroud)

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

PS与"var"一切正常!!!

Cid*_*Cid 4

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

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);
Run Code Online (Sandbox Code Playgroud)

您仍然可以以编程方式检查变量是否存在或不使用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 :)");
Run Code Online (Sandbox Code Playgroud)

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