试图了解我的JS时钟上的错误

时间:2018-12-09 17:44:15

标签: javascript

我试图完成一个针对JavaScript的OpenClassRoom练习,在此练习中,您必须编写一些代码,这些代码将在一秒钟内“告诉您”,所以这里有我的代码,但是当我运行它时,我有一个错误:Uncaught ReferenceError:heures未在:6:18定义

    let heures = 14;
    let minutes = 17;
    let secondes = 59;

    if ((minutes === 59) && (secondes === 59))
      {
        let heures = Number(heures)+1
        let minutes = 00
        let secondes = 00
        console.log(heures+":"+minutes+":"+secondes) 
      }

    else if ((secondes === 59) && (minutes !== 59))
      {
        let heures = heures
        let minutes = minutes+1
        let secondes = 00
        console.log(heures+":"+minutes+":"+secondes) 
      }

    else if ((heures === 23) && (minutes === 59) && (secondes === 59))
      {
        let heures = 00
        let minutes = 00
        let secondes = 00
        console.log(heures+":"+minutes+":"+secondes) 
      }
  
    else if ((heures !== 23) && (minutes !== 59) && (secondes !== 59))
      {
        let heures = heures
        let minutes = minutes
        let secondes = secondes + 1
        console.log(heures+":"+minutes+":"+secondes) 
      }

感谢您的帮助,对不起我的英语

1 个答案:

答案 0 :(得分:0)

您正在使用let重新声明变量,这是导致错误的原因。 let用于创建“块作用域变量”,并且由于您在if语句的不同块中使用了它,因此实际上您在创建具有相同名称但作用域不同的不同变量。

您只需要声明一次变量,然后就可以根据需要为它重新分配一个值。

let heures = 14;
let minutes = 17;
let secondes = 59;

if ((minutes === 59) && (secondes === 59)) {
   heures = Number(heures) + 1;
   minutes = 00;
   secondes = 00;
   //console.log(heures+":"+minutes+":" + secondes) ;
} else if ((secondes === 59) && (minutes !== 59)) {
   //heures = heures; <-- Setting a variable to itself makes no change to the program
   minutes = minutes + 1;
   secondes = 00;
   //console.log(heures+":"+minutes+":"+secondes) ;
} else if ((heures === 23) && (minutes === 59) && (secondes === 59)) {
   heures = 00;
   minutes = 00;
   secondes = 00;
   //console.log(heures+":"+minutes+":"+secondes) ;
} else if ((heures !== 23) && (minutes !== 59) && (secondes !== 59)) {
   //heures = heures;    <-- Setting a variable to itself makes no change to the program
   //minutes = minutes;  <-- Setting a variable to itself makes no change to the program
   secondes = secondes + 1;
   //console.log(heures+":" + minutes + ":" + secondes);
}
// No need to have this in each branch of the if statement
// when you want to do it in all cases.
console.log(heures+":" + minutes + ":" + secondes);