我想创建一个MaxMinAvgSum的函数,但问题是,当用户在所有文本字段中输入数字时,它会给出准确的结果。
但是,当TextField 3为空时,不会给出准确的结果。我尝试处理此事,但没有任何反应。



function maxer() {

  var max = 0,
    min = 0,
    sum = 0,
    avg, power = "<p>MAX:";
  var arrayName = [3];
  arrayName[0] = document.getElementById('number1').value;
  arrayName[1] = document.getElementById('number2').value;
  arrayName[2] = document.getElementById('number3').value;

  if (arrayName[2] == "") {
    arrayName[2] = 0;
  }

  var f = Math.max(arrayName[0], arrayName[1], arrayName[2]);
  max = f;

  var g = Math.min(arrayName[0], arrayName[1], arrayName[2]);
  min = g;


  for (var i = 0; i < arrayName.length; sum = sum + parseInt(arrayName[i]), avg = sum / arrayName.length,
    i++);

  power += max + "</p>" + "<br/>";
  power += "<p>Min:";
  power += min + "</p>" + "<br/>";
  power += "<p>SUM:";
  power += sum + "</p>" + "<br/>";
  power += "<p>AVERAGE:";
  power += avg + "</p>" + "<br/>";
  document.getElementById('mmsa').innerHTML = power;
}


Enter Number 1: <input id="number1" type="text" name="number1" placeholder="Enter Number 1" />
Enter Number 2: <input id="number2" type="text" name="number2" placeholder="Enter Number 2" />
Enter Number 3: <input id="number3" type="text" name="number3" placeholder="Enter Number 3" />
<button type="button" onClick="maxer()">Click This To Operate</button>
<p id="mmsa"></p>

最佳答案

简而言之,您只需要处理包含值的数组元素。理想情况下,您的数组应该只大一些,因为它需要保存有效的输入值。 Oriol的解决方案以一种非常干净和紧凑的方式实现了这一目标,但是如果您不熟悉Javascript,可能很难理解。如果您想要更接近原始解决方案的方法,那么可以使用一种(稍微不太干净)的替代方法,该替代方法使用尽可能多的原始代码:



function maxer() {

    var max = 0,
      min = 0,
      sum = 0,
      avg, power = "<p>MAX:";
    var arrayName = [];
    for(var i=1;i<=3;i++)
    {
        if(document.getElementById('number' + i).value.trim().length > 0)
        {
            arrayName[arrayName.length] = parseInt(document.getElementById('number' + i).value);
        }
    }

    if(arrayName.length > 0)
    {
        max = arrayName[0];
        min = arrayName[0];
        sum = arrayName[0];

        for (var j = 1; j < arrayName.length; j++)
        {
            max = Math.max(max, arrayName[j]);
            min = Math.min(min, arrayName[j]);
            sum += arrayName[j];
        }

        var avg = sum / arrayName.length;

        power += max + "</p>" + "<br/>";
        power += "<p>Min:";
        power += min + "</p>" + "<br/>";
        power += "<p>SUM:";
        power += sum + "</p>" + "<br/>";
        power += "<p>AVERAGE:";
        power += avg + "</p>" + "<br/>";
        document.getElementById('mmsa').innerHTML = power;
    }
}

Enter Number 1: <input id="number1" type="text" name="number1" placeholder="Enter Number 1" />
Enter Number 2: <input id="number2" type="text" name="number2" placeholder="Enter Number 2" />
Enter Number 3: <input id="number3" type="text" name="number3" placeholder="Enter Number 3" />
<button type="button" onClick="maxer()">Click This To Operate</button>
<p id="mmsa"></p>

10-08 12:00