如果,否则,语句:未捕获ReferenceError:分配中的左侧无效

时间:2019-02-20 17:11:32

标签: javascript

我刚刚开始编写Javascript,但我不断收到语法错误,但没有设法找出它的来源。这是我写的代码片段:

let num1 = 5;
let num2 = 8;
let num3 = 10;

if (num1 === num2) {
  console.log("the comparison shows");
} else if (num1 > num2 = true); {
  console.log("Number 1 is greater than number 2. The value for num 1 is " + num1);
} else(num2 > num1 = true); {
  console.log("Number 2 is greater and the value is " + num2);

2 个答案:

答案 0 :(得分:1)

在else if和else块之后删除;,无需在else-if / else语句中将表达式等同为true。 else语句中不需要条件。如果以上任何一项均未通过,则控件将仅转到其他

let num1 = 5;
let num2 = 8;
let num3 = 10;
if (num1 === num2) {
  console.log("the comparison shows");
} 
else if (num1 > num2) {
  console.log("Number 1 is greater than number 2. The value for num 1 is " + num1);
} 
else
  console.log("Number 2 is greater and the value is " + num2);

答案 1 :(得分:1)

以下是您的代码有问题:

  1. 您在不应该使用的条件结束时使用;
  2. 您正在为else设置条件。当未执行前一个else块时,将执行if
  3. num1 > num2返回Boolean。您需要使用=====而非赋值运算符=进行比较。您不需要将它们与true进行比较,因为它们是Boolean

let num1 = 5;
let num2 = 8;
let num3 = 10;

if (num1 === num2){ 
  console.log("the comparison shows");
}
else if (num1 > num2 === true) {
  console.log("Number 1 is greater than number 2. The value for num 1 is " + num1);
} 
else {
  console.log("Number 2 is greater and the value is " + num2);
}