--- id: 587d7b87367417b2b2512b40 title: Compare Scopes of the var and let Keywords challengeType: 1 videoUrl: '' localeTitle: 比较var的范围并让关键字 --- ## Description
使用var关键字声明变量时,它将全局声明,如果在函数内声明,则声明为本地。 let关键字的行为类似,但具有一些额外的功能。在块,语句或表达式中使用let关键字声明变量时,其范围仅限于该块,语句或表达式。例如:
var numArray = [];
for(var i = 0; i <3; i ++){
numArray.push(ⅰ);
}
的console.log(numArray);
//返回[0,1,2]
的console.log(ⅰ);
//返回3
使用var关键字, i被全局声明。因此,当执行i++时,它会更新全局变量。此代码类似于以下内容:
var numArray = [];
var i;
for(i = 0; i <3; i ++){
numArray.push(ⅰ);
}
的console.log(numArray);
//返回[0,1,2]
的console.log(ⅰ);
//返回3
如果您要创建一个函数并将其存储以供以后在使用i变量的for循环中使用,则此行为将导致问题。这是因为存储的函数将始终引用更新的全局i变量的值。
var printNumTwo;
for(var i = 0; i <3; i ++){
if(i === 2){
printNumTwo = function(){
回归我;
};
}
}
的console.log(printNumTwo());
//返回3
正如你所看到的, printNumTwo()打印3,而不是2.这是因为分配给该值i进行了更新和printNumTwo()返回全球i ,而不是价值i的作用是在创建for循环的时候了。 let关键字不遵循此行为:
'使用严格';
让printNumTwo;
for(let i = 0; i <3; i ++){
if(i === 2){
printNumTwo = function(){
回归我;
};
}
}
的console.log(printNumTwo());
//返回2
的console.log(ⅰ);
//返回“我没有定义”
i没有定义,因为它没有在全局范围内声明。它仅在for循环语句中声明。 printNumTwo()返回正确的值,因为循环语句中的let关键字创建了具有唯一值(0,1和2)的三个不同的i变量。
## Instructions
修复代码,以便i在if语句中声明的是一个单独的变量,而不是i在函数的第一行声明的变量。确保不要在代码中的任何位置使用var关键字。本练习旨在说明varlet关键字如何将范围分配给声明的变量之间的区别。在编写与本练习中使用的函数类似的函数时,通常最好使用不同的变量名来避免混淆。
## Tests
```yml tests: - text: var在代码中不存在。 testString: 'getUserInput => assert(!getUserInput("index").match(/var/g),"var does not exist in code.");' - text: 在if语句中声明的变量i应该等于“块范围”。 testString: 'getUserInput => assert(getUserInput("index").match(/(i\s*=\s*).*\s*.*\s*.*\1("|")block\s*scope\2/g), "The variable i declared in the if statement should equal "block scope".");' - text: checkScope()应该返回“函数范围” testString: 'assert(checkScope() === "function scope", "checkScope() should return "function scope"");' ```
## Challenge Seed
```js function checkScope() { "use strict"; var i = "function scope"; if (true) { i = "block scope"; console.log("Block scope i is: ", i); } console.log("Function scope i is: ", i); return i; } ```
## Solution
```js // solution required ```