首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >需要帮助在java脚本中找到max值(没有max方法)

需要帮助在java脚本中找到max值(没有max方法)
EN

Stack Overflow用户
提问于 2021-03-22 15:40:41
回答 4查看 88关注 0票数 2

首先,我想说非常感谢你的来访。我是Javascript的初学者。现在处理一些问题,我需要帮助找出我的台词出了什么问题。所以在这里,我想用一个函数中的条件语句从变量中找出最高的数字,我现在被卡住了。

编辑:谢谢你们帮助我,现在我对我应该学到的东西有了清晰的认识。

代码语言: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}`);```
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2021-03-22 15:59:13

正如注释中指出的,您的代码有一些错误,所以问题不是100%清楚,所以我向您介绍以下方法.

代码语言:javascript
复制
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;
}

此函数接受要与之比较的无穷多个参数,并且不限制输入的固定数量。例如,以下都是有效的用途:

代码语言:javascript
复制
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.

代码语言:javascript
复制
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;
}

一个完整的工作示例:

代码语言:javascript
复制
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}`);

票数 0
EN

Stack Overflow用户

发布于 2021-03-22 15:49:55

使用let关键字声明的变量具有块作用域,也就是说,它们只能在定义在其中的块中访问。首先将max设置为a,然后在if语句中创建另一个具有相同名称的局部变量,并将其赋值为b。您应该做的是删除if/ the语句中的let声明。

其次,当满足第一个条件时,您的if块将退出。您应该使用另一个if语句(它将运行,而不管第一个语句中的条件是否满足),而不是一个one语句(只有当第一个条件没有满足时才会运行)。

第三,在console.log中传递对函数的对象引用(所有函数都是javascript中的对象),这相当于函数文本。您需要传递函数调用。

除了不使用未定义的变量之外,这就是您需要做的全部工作。

代码语言: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)}`);

票数 1
EN

Stack Overflow用户

发布于 2021-03-22 15:49:05

我看到很多错误。首先,初始化最多2次。let max = a;,然后您可以使用max。但else if也错了。

如果是c < b < a呢?则只有第一个如果应用,尽管c大于

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66749315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档