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

时间:2018-09-12 09:56:20

标签: javascript variables ecmascript-6 let

如果我打开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”声明? /如何确定是否定义了let var(声明?)

P.S 与“无功”一切正常!!!

1 个答案:

答案 0 :(得分: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);

您仍然可以使用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