首先,我想说非常感谢你的来访。我是Javascript的初学者。现在处理一些问题,我需要帮助找出我的台词出了什么问题。所以在这里,我想用一个函数中的条件语句从变量中找出最高的数字,我现在被卡住了。
编辑:谢谢你们帮助我,现在我对我应该学到的东西有了清晰的认识。
const number1 = 103;
const number2 = 72;
const number3 = 189;
const getMax = (a, b, c) => {
let max = a;
if(b > max) {
let max = b;
} else if (c > max){
let max = c;
};
return max;
}
getMax(number1, number2, number3);
console.log(`Max number is ${getMax}`);```发布于 2021-03-22 15:59:13
正如注释中指出的,您的代码有一些错误,所以问题不是100%清楚,所以我向您介绍以下方法.
function getMax() {
const nums = arguments;
var max = null;
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
if (max === null || num > max) {
max = num;
}
}
return max;
}此函数接受要与之比较的无穷多个参数,并且不限制输入的固定数量。例如,以下都是有效的用途:
const validExample1 = getMax(33, 72, 189, 4, 1); // Output: 189
const validExample2 = getMax(2, 2); // Output: 2
const validExample3 = getMax(320, 1, 8); // Output: 320
const validExample4 = getMax(-1, -200, -34); // Output: -1通过不使用箭头函数表达式,您可以使用arguments关键字检索所有值的可迭代对象。或者,如果要求使用箭头函数,您可以简单地使用扩展语法(.) do.
const getMax = ( ...nums ) => {
var max = null;
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
if (max === null || num > max) {
max = num;
}
}
return max;
}一个完整的工作示例:
const number1 = 3;
const number2 = 72;
const number3 = 189;
function getMax() {
const nums = arguments;
var max = null;
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
if (max === null || num > max) {
max = num;
}
}
return max;
}
const result = getMax(number1, number2, number3);
console.log(`Nilai maksimum adalah ${result}`);
发布于 2021-03-22 15:49:55
使用let关键字声明的变量具有块作用域,也就是说,它们只能在定义在其中的块中访问。首先将max设置为a,然后在if语句中创建另一个具有相同名称的局部变量,并将其赋值为b。您应该做的是删除if/ the语句中的let声明。
其次,当满足第一个条件时,您的if块将退出。您应该使用另一个if语句(它将运行,而不管第一个语句中的条件是否满足),而不是一个one语句(只有当第一个条件没有满足时才会运行)。
第三,在console.log中传递对函数的对象引用(所有函数都是javascript中的对象),这相当于函数文本。您需要传递函数调用。
除了不使用未定义的变量之外,这就是您需要做的全部工作。
const number1 = 54;
const number2 = 72;
const number3 = 189;
const getMax = (a, b, c) => {
let max = a;
if(b > max) {
max = b;
}
if (c > max){
max = c;
};
return max;
}
console.log(`Nilai maksimum adalah ${getMax(number1, number2, number3)}`);
发布于 2021-03-22 15:49:05
我看到很多错误。首先,初始化最多2次。let max = a;,然后您可以使用max。但else if也错了。
如果是c < b < a呢?则只有第一个如果应用,尽管c大于
https://stackoverflow.com/questions/66749315
复制相似问题