JS:如何防止 let 重复声明? / 判断是否定义了 let 变量
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" 声明? / 如何确定一个 let var 是否被定义(声明?)
P.S
"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
如果我打开 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 "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