[英]Code working with ternary operator but not with if else statements
This javascript program works with ternary operator as expected but not with if else statements. 此javascript程序可以按预期与三元运算符一起使用,但不能与if else语句一起使用。 What I am doing wrong?
我做错了什么?
I am trying to solve some basic javascript exercises but I am stuck at this question. 我正在尝试解决一些基本的javascript练习,但是我陷于这个问题。 https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-74.php
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]));
// With if-else statement //使用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]));
You should be assigning the value in the body of the if/else statement, not within the comparison, so something like this should work for you: 您应该在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]));
Below code works 下面的代码有效
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]));
calculate max_val outside if condition and put result in if condition let max_val = nums[0] > nums[2] 在条件之外计算max_val,在条件条件下放入结果let max_val = nums [0]> nums [2]
Variable declaration within if
statement not allowed. 不允许在
if
语句中进行变量声明。 Remove it. 去掉它。
Try this if you want only max value 如果只想要最大值,请尝试此
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]));
if you want all the elements in the array to be set to max value, then use this 如果要将数组中的所有元素都设置为最大值,请使用此方法
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]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.