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

问题描述 投票:0回答:3

这个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]));
javascript ecmascript-6 ternary-operator
3个回答
4
投票

你应该在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]));

1
投票

下面的代码工作

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

如果条件,则计算max_val outside并在条件设为max_val = nums [0]> nums [2]时放入结果


0
投票

不允许在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]));
© www.soinside.com 2019 - 2024. All rights reserved.