【问题标题】:Find the largest number in an array of integers javascript查找整数数组中的最大数 javascript
【发布时间】:2018-08-27 15:36:30
【问题描述】:

您好,我对 javascript 有一定的了解,我在这里得到了帮助,这非常有帮助(谢谢大家!)但它仍然非常有限和基本。基本上下面是我将提示一个显示值答案的弹出窗口。事情来自我在下面找到的编码,如果我必须插入一个数组,比如说12,8,3,2,输出将是8。出于某种原因,下面的代码只考虑了 1 位数字。有没有办法编辑此代码,以便上面输入的答案是12

再次感谢!

我已经完成了相当一部分的研究:

代码:

<html><head>

  <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
  <title>test</title>


</head><body>
<br>

<script type="text/javascript">
    function evaluate() {
  const input = prompt("Please enter the array of integers in the form: 1,2,3,1")
    .split(',')
    .map(nums => nums.trim());

  function max(numArray) 
{
    var nums = numArray.slice();
    if (nums.length == 1) { return nums[0]; }
    if (nums[0] < nums[1]) { nums.splice(0,1); }
    else { nums.splice(1,1); }
    return max(nums);
}


  if (input == "" || input == null) {
            document.writeln("Sorry, there is nothing that can be calculated.");
        } else {    

  document.writeln("The largest number is: ");
  document.writeln(max(input) + " with a starting input string of: " + input);
}
}
  </script>

<script type="text/javascript">
    evaluate();
  </script>

</body></html>

【问题讨论】:

  • 你在提示框中输入了什么?
  • 一个小改动就能解决它....map(nums =&gt; number(nums.trim()));

标签: javascript html integer syntax-error


【解决方案1】:

你可以使用Math.max(...array)函数

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

const returnMax = (str='') => { // pass string
    const numbersArr = str.trim().split(',').map(num => parseInt(num.trim()));
    return Math.max(...numbersArr); // rest-spread operator from es6 syntax
}

更多关于休息运算符:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

【讨论】:

  • 您好,谢谢,但它必须使用递归。我没有在标题中指定。不过谢谢
【解决方案2】:

问题是你比较的是字符串而不是整数。因此,它仅比较“数字”的第一个字符,在您的情况下 12 与 8 将导致 8 大于 1(12 的第一个字符)。在进行比较之前,请确保将字符串更改为整数。您只需要更改一行:

if (nums[0] &lt; nums[1])

if (parseInt(nums[0]) &lt; parseInt(nums[1]))

JSFiddle:https://jsfiddle.net/omartanti/ahbtg2z2/1/

请注意:如果第一个字符不能转换为数字,则 parseInt 返回 NaN

【讨论】:

    【解决方案3】:

    您可以使用Math.max 和扩展运算符(...) 来获取最大值。在sn-p 中+num.trim() 会将字符串转换为数字

    function evaluate() {
      const input = prompt("Please enter the array of integers in the form: 1,2,3,1")
        .split(',')
        .map(nums => +nums.trim());
      console.log(input)
      var getLargest = Math.max(...input);
      console.log(getLargest)
    }
    
    evaluate();

    【讨论】:

    • 您好,谢谢,但它必须使用递归。我没有在标题中指定。不过谢谢
    猜你喜欢
    • 2015-10-30
    • 2015-07-04
    • 1970-01-01
    • 2012-09-04
    • 2016-05-25
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多