简体   繁体   English

什么时候用 let 什么时候还应该用 var

[英]When to use let and when should we still use var

I read an article that we don't need to use var keyword anymore but I ran into a problem in my code where I could not use my variable inside an if block because I had declared it using let.我读了一篇我们不再需要使用 var 关键字的文章,但我在代码中遇到了一个问题,我无法在 if 块中使用我的变量,因为我已经使用 let 声明了它。

How could I solve this problem if we don't need to use var?如果我们不需要使用var,我该如何解决这个问题?

let elementWidth = el.getBoundingClientRect().width
let windowWidth = window.width // 400 px

if (windowWidth > elementWidth) {
    elementWidth += 200
}

console.log(elementWidth) // 400 px

"let" variable will not change the values outside of block scope as if, for statement "let" 变量不会像 for 语句那样更改块范围之外的值

for( let j = 0; j < 3; j++ ) {
    console.log(i);// i = 3
};
console.log(j); //undefined

"var" is for function scope, a global scope like “var”用于函数作用域,一个全局作用域,如

    for( var i= 0; i < 3; i++ ) {
    console.log(i);
};
console.log(i);// i = 3

for more https://edgecoders.com/function-scopes-and-block-scopes-in-javascript-25bbd7f293d7更多https://edgecoders.com/function-scopes-and-block-scopes-in-javascript-25bbd7f293d7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM