javascript - 代码适用于三元运算符,但不适用于 if else 语句

标签 javascript ecmascript-6 ternary-operator

此 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]));

关于javascript - 代码适用于三元运算符,但不适用于 if else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55624587/

相关文章:

javascript - Phaser.io - 是否可以使用补间将tileSprite.tilePosition移动到特定目标?

javascript - 通过分解寻找完美立方体的程序

reactjs - Redux - 如何在 reducer 中向数组添加条目

php - 三元运算符。有可能单方面行动吗?

javascript - ECMAScript 6 或 7 是否支持静态类型?

javascript - Vue2 组件以某种方式修改 prop

javascript - 什么是解构赋值及其用途?

javascript - Javascript 中优雅的数组转换

java - 为什么三元运算符会因类型不匹配错误而失败?

javascript - 如何理解这个逻辑和三元运算符的例子?