了解设定范围

问题描述:

我对代码的假设是第二个let x上面的代码位于时间死区。因此不应该抛出错误。了解设定范围

代码

function f(condition, x) { 
 
    if (condition) { 
 
    let x = 100; 
 
    return x; 
 
    } 
 
    let x = 30; // <---- throw error 
 

 
    return x; 
 
} 
 

 
f(true, 1);

+2

'let'是 “块作用域” - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/发言/让 –

+1

我知道让是块范围 – aWebDeveloper

+0

阅读关于在Javascript中提升,所以你可以了解哪些代码的例子失败。 – Dez

那么这里的问题是,你重新声明同一变量x两次在同一function,所以变量x将被吊起。

if (condition) { 
    //This x declaration is fine as it wasn't preceded with any others declaration inside the same block scope 
    let x = 100; 
    return x; 
    } 
    //Now this second x declaration will cause the hoisting problem 
    let x = 30; // <---- throw error 

这里第二let x = 30;声明冲顶您function范围x变量。所以得出的结论是,你不能在同一个范围内多次声明同一个变量。

有关在Javascript varaible提升进一步的阅读,您可以检查:

+1

你可以取出'if(condition)'位,因为它不是它抱怨的'x'。例如。这很好'{let x = 0; {let x = 0; }}' – Keith

+1

这是错误的。 'let' /'const'没有提升。这个问题是由传入的参数'x'导致的,它与第二个'let'声明在相同的范围内。 'let' /'const'意味着你只能在同一个范围内绑定一个名字('x')。 – ftor

问题似乎是与X已经是具有相同的范围,因为外X一个函数参数。如果我更改功能参数xy,代码工作正常。

代码

function f(condition, y) { 
 
    if (condition) { 
 
    let x = 100; 
 
    return x; 
 
    } 
 
    let x = 30; // <---- doesnt throw error 
 

 
    return x; 
 
} 
 

 
f(true, 1);