【发布时间】:2019-09-01 14:56:42
【问题描述】:
这个 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]));
【问题讨论】:
-
第二个版本中有
return语句。return语句立即退出函数。 -
variable assignment inside if it statement太丑了 -
@Pointy 即使在删除 return 语句后也不走运
-
@CodeManiac 好点。将其移到 if 语句之外
标签: javascript ecmascript-6 ternary-operator