4.1 KiB
4.1 KiB
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d7b87367417b2b2512b40 | Compare Scopes of the var and let Keywords | 1 | 比较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
关键字。本练习旨在说明var
和let
关键字如何将范围分配给声明的变量之间的区别。在编写与本练习中使用的函数类似的函数时,通常最好使用不同的变量名来避免混淆。 Tests
tests:
- text: <code>var</code>在代码中不存在。
testString: 'getUserInput => assert(!getUserInput("index").match(/var/g),"<code>var</code> does not exist in code.");'
- text: 在if语句中声明的变量<code>i</code>应该等于“块范围”。
testString: 'getUserInput => assert(getUserInput("index").match(/(i\s*=\s*).*\s*.*\s*.*\1("|")block\s*scope\2/g), "The variable <code>i</code> declared in the if statement should equal "block scope".");'
- text: <code>checkScope()</code>应该返回“函数范围”
testString: 'assert(checkScope() === "function scope", "<code>checkScope()</code> should return "function scope"");'
Challenge Seed
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
// solution required