此 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/