学习JS ...似乎停留在此练习上...不确定我在做什么错

时间:2019-10-22 18:21:30

标签: javascript

这是在线课程的练习...不确定我在做什么错。我应该做的措辞还不够详细。

function exerciseFour(value){
  let greaterThanFive = false;
  // In this exercise, you will be given a variable, it will be called: value
  // You will also be given a variable named: greaterThanFive
  // Using an 'if' statement check to see if the value is greater than 5. If it is, re-assign greaterThanFive the boolean true.
  if (value > 5) {
    let greaterThanFive = true;
  }

  // Please write your answer in the line above.
  return greaterThanFive;
}

function exerciseFive(name){
  let isSondra = false;
  // In this exercise, you will be given a variable, it will be called: name
  // You will also be given a variable named: isSondra
  // Using an 'if' statement check to see if the name is equal to the string 'Sondra'. If it is, re-assign isSondra the boolean true.
  if (name === 'Sondra') {
    let isSondra = true;
  }

  // Please write your answer in the line above.
  return isSondra;
}

2 个答案:

答案 0 :(得分:0)

您不能第二次声明变量

删除第二个let将解决您的问题。

function exerciseFour(value){
  let greaterThanFive = false;

  if (value > 5) {
     greaterThanFive = true; // <--- Remove `let` here.
  }

  return greaterThanFive;
}

function exerciseFive(name){
  let isSondra = false;

  if (name === 'Sondra') {
     isSondra = true;
  }

  return isSondra;
}

console.log(exerciseFour(3));
console.log(exerciseFour(7));
console.log(exerciseFive("Matt"));
console.log(exerciseFive("Sondra"));

答案 1 :(得分:0)

let关键字在词法范围中定义了一个新变量。在此行的情况下的词汇范围:

function exerciseFour(value){
  let greaterThanFive = false;   // <----
  // ...
}

...是函数。第二个let然后是阴影第一个变量,这意味着嵌套词法作用域具有一个具有相同名称但与原始变量完全分离的变量。它的范围是if语句块:

function exerciseFour(value){
  let greaterThanFive = false; // <-- scoped to function
  if (value > 5) {
    let greaterThanFive = true;  // <-- define new variable, scoped to if statement
  }

  return greaterThanFive;
}

因此,一旦我们离开 if语句块的范围,greaterThanFive就会引用 function-scoped 变量,这就是为什么它仍然具有值的原因false

仅删除第二个let会使该语句成为赋值语句,而不是变量声明

function exerciseFour(value){
  let greaterThanFive = false;
  if (value > 5) {
    greaterThanFive = true; // Assigns a new value to the variable
  }

  return greaterThanFive;
}