freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../es6/compare-scopes-of-the-var-a...

4.1 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7b87367417b2b2512b40 Compare Scopes of the var and let Keywords 1 比较var的范围并让关键字

Description

使用var关键字声明变量时,它将全局声明,如果在函数内声明,则声明为本地。 let关键字的行为类似,但具有一些额外的功能。在块,语句或表达式中使用let关键字声明变量时,其范围仅限于该块,语句或表达式。例如:
var numArray = [];
forvar i = 0; i <3; i ++{
numArray.push;
}
的console.lognumArray;
//返回[0,1,2]
的console.log;
//返回3
使用var关键字, i被全局声明。因此,当执行i++时,它会更新全局变量。此代码类似于以下内容:
var numArray = [];
var i;
fori = 0; i <3; i ++{
numArray.push;
}
的console.lognumArray;
//返回[0,1,2]
的console.log;
//返回3
如果您要创建一个函数并将其存储以供以后在使用i变量的for循环中使用则此行为将导致问题。这是因为存储的函数将始终引用更新的全局i变量的值。
var printNumTwo;
forvar i = 0; i <3; i ++{
ifi === 2{
printNumTwo = function{
回归我;
};
}
}
的console.logprintNumTwo;
//返回3
正如你所看到的, printNumTwo()打印3而不是2.这是因为分配给该值i进行了更新和printNumTwo()返回全球i ,而不是价值i的作用是在创建for循环的时候了。 let关键字不遵循此行为:
'使用严格';
让printNumTwo;
forlet i = 0; i <3; i ++{
ifi === 2{
printNumTwo = function{
回归我;
};
}
}
的console.logprintNumTwo;
//返回2
的console.log;
//返回“我没有定义”
i没有定义因为它没有在全局范围内声明。它仅在for循环语句中声明。 printNumTwo()返回正确的值,因为循环语句中的let关键字创建了具有唯一值0,1和2的三个不同的i变量。

Instructions

修复代码,以便i在if语句中声明的是一个单独的变量而不是i在函数的第一行声明的变量。确保不要在代码中的任何位置使用var关键字。本练习旨在说明varlet关键字如何将范围分配给声明的变量之间的区别。在编写与本练习中使用的函数类似的函数时,通常最好使用不同的变量名来避免混淆。

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