[英]difference between 'let' and 'var' inside a function which has a switch case
i was working on a functionality, i have found an issue while using let inside the switch case of a function. 我正在研究某个功能,但在功能的开关盒内使用let时发现一个问题。 if i change to var it works.
如果我更改为var,它可以工作。 I have read difference between the let and var.
我已经读过let和var之间的区别。 But is this case is causing issue of block level scope.
但是这种情况是否引起了块级范围的问题。 Little bit confused.
有点困惑。
Any help appreciated 任何帮助表示赞赏
var a = "sample data" const returnDataOfLet = (a) => { switch(typeof a){ case "string": let a = a.split(" ") // will throw an error change let to var it will work return a } } console.log(returnDataOfLet(a))
Inside the block you declare let a
. 在块内声明
let a
。 This creates a new variable a
. 这将创建一个新变量
a
。
Then you call a.split
. 然后调用
a.split
。 This throws an error because a
is undefined
(it has to be undefined
: you haven't give it a value yet). 这会引发错误,因为
a
是undefined
(它必须是undefined
:您尚未给它赋值)。
The program stops at the point because of the exception. 程序由于异常而停止。
If you use var
instead of let
, then the var
is ignored completely because there is already an a
declared in that scope. 如果使用
var
而不是let
,则将完全忽略var
因为该作用域中已经有a
声明。
Since you haven't created a new variable, a
is the argument you passed to the function. 由于尚未创建新变量,因此
a
是您传递给函数的参数。
This is a string, so you can call split
on it and assign the result back to the a
variable declared in the argument list. 这是一个字符串,那么你可以调用
split
它,然后将结果返回到a
参数列表声明的变量。
Here is a elaborate guide on this topic. 这是有关此主题的详尽指南。 Generally:
通常:
The way you use let here, the variable is redeclared at any iteration, that causes the error. 在这里使用let的方式,在任何迭代中都会重新声明变量,这会导致错误。 You can always reassign the value of a though.
您始终可以重新分配虽然值。
let a = "sample data"; const returnDataOfLet = (a) => { switch (typeof a) { case "string": return a.split(" "); } } console.log(returnDataOfLet(a));
The globally defined var a
is not the same a which is passed to the function as parameter
. 全局定义的
var a
与作为parameter
传递给函数的a不同。 Its just like an alias
for a variable
. 就像
variable
的alias
一样。 and also in case "
string "
no need to again create a
as it is already there in the function. 并且在
case "
string "
case "
也不需要再次创建a
因为它已经存在于函数中。 Here it is not a problem with scopes
but definition
and parameters
. 在这里,
scopes
不是问题,而是definition
和parameters
。
var a = "sample data" const returnDataOfLet = (a) => { switch(typeof a){ case "string": a = a.split(" ") // will throw an error change let to var it will work return a } } console.log(returnDataOfLet(a))
If you want to use let
use another variable name 如果你想使用
let
使用另一个变量名
var a = "sample data" const returnDataOfLet = (a) => { switch(typeof a){ case "string": let b = a.split(" ") // will throw an error change let to var it will work return b } } console.log(returnDataOfLet(a))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.