使用三元运算符但不使用 if else 语句的代码

Code working with ternary operator but not with if else statements

此 javascript 程序按预期使用三元运算符,但不适用于 if else 语句。我做错了什么?

我正在尝试解决一些基本的 javascript 练习,但我被困在这个问题上。 https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-74.php

//Working code with ternary operator
    function all_max(nums) {
      var max_val = nums[0] > nums[2] ? nums[0] : nums[2];

      nums[0] = max_val;
      nums[1] = max_val;
      nums[2] = max_val;

      return nums;
      }
    console.log(all_max([20, 30, 40]));
    console.log(all_max([-7, -9, 0]));
    console.log(all_max([12, 10, 3]));

// 带 if-else 语句

  function all_max(nums) {
     if (var max_val = nums[0] > nums[2]) {
     return nums[0];
    } else {
     return nums[2];
  }

     nums[0] = max_value ;
     nums[1] = max_value ;
     nums[2] = max_value ;

return nums;
}
console.log(all_max([20, 30, 40]));
console.log(all_max([-7, -9, 0]));
console.log(all_max([12, 10, 3]));

您应该在 if/else 语句的主体中分配值,而不是在比较中,所以这样的事情应该适合您:

function all_max(nums) {
  let max_val = 0
  if (nums[0] > nums[2]) {
    max_val = nums[0];
  } else {
    max_val = nums[2];
  }
  nums[0] = max_val;
  nums[1] = max_val;
  nums[2] = max_val;

  return nums;
}

console.log(all_max([20, 30, 40]));
console.log(all_max([-7, -9, 0]));
console.log(all_max([12, 10, 3]));

下面的代码有效

      function all_max(nums) {
let max_val = nums[0] > nums[2]
     if (max_val) {
     return nums[0];
    } else {
     return nums[2];
  }

     nums[0] = max_value ;
     nums[1] = max_value ;
     nums[2] = max_value ;

return nums;
}
console.log(all_max([20, 30, 40]));
console.log(all_max([-7, -9, 0]));
console.log(all_max([12, 10, 3]));

在 if 条件外计算 max_val 并将结果放入 if 条件 让 max_val = nums[0] > nums[2]

不允许在 if 语句中声明变量。删除它。

如果你只想要最大值,试试这个

 function all_max(nums) {
   if (nums[0] > nums[2]) {
         max_value =  nums[0];
   } else {
         max_value = nums[2];
   }
   return max_value;
 } 
 console.log(all_max([20, 30, 40]));
 console.log(all_max([-7, -9, 0]));
 console.log(all_max([12, 10, 3]));

如果你想让数组中的所有元素都设置为最大值,那么使用这个

function all_max(nums) {
     if (nums[0] > nums[2]) {
             max_value =  nums[0];
     } else {
             max_value = nums[2];
     }
     nums[0] = max_value;
     nums[1] = max_value;
     nums[2] = max_value;
     return nums;
}
console.log(all_max([20, 30, 40]));
console.log(all_max([-7, -9, 0]));
console.log(all_max([12, 10, 3]));