来自Array,JavaScript的Sum值

时间:2017-05-02 09:34:02

标签: javascript arrays

提示用户输入许多输入,将其存储在数组中,然后打印求和,平均值,最大数量,最小数量和大于平均数量的数字。 我已经定义了一个名为magicnumber的JavaScript变量,它是一个新的数组,并打印数组的值,如下所示:

var magicnumber = [];

mymagicNumber();

function mymagicNumber() {
  //Specify the size of array
  var size = parseInt(prompt("How many data values do you need have?"));
  for (var i = 1; i <= size; i++) {
    //sorted in array
    var num = parseInt(magicnumber.push(prompt("Enter data value number " + i)));
    var s = magicnumber.join(', ');
  }
  //Display array element
  document.getElementById("demo1").innerHTML = "Your data : " + s + "<br>";
}
<div id="demo1"></div>

我怎么能总结呢?

2 个答案:

答案 0 :(得分:0)

以下是另外两种查找求和的方法,不使用for循环。

&#13;
&#13;
var magicnumber = [];

function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));

for (var i = 1; i <= size; i++) {
	//sorted in array
	var num = magicnumber.push(parseInt(prompt("Enter data value number " + i)));
}

var data = magicnumber.join(', ');
var s1 = magicnumber.reduce(function(acc, val) {
	return acc + val;
});

var s2 = eval(magicnumber.join("+"));


//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + data + "<br>";
document.getElementById("demo2").innerHTML = "Sum is: " + s1 + "<br>";
document.getElementById("demo3").innerHTML = "Sum is: " + eval(s2) + "<br>";
}

mymagicNumber();
&#13;
<div id="demo1"></div>
<div id="demo2"></div>
<div id="demo3"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用Array#reduce()获取总和

&#13;
&#13;
var magicnumber = [];

mymagicNumber();

function mymagicNumber() {
  //Specify the size of array
  var size = parseInt(prompt("How many data values do you need have?"));
  for (var i = 1; i <= size; i++) {
    var promptValue = prompt("Enter data value number " + i);
    magicnumber.push(+promptValue);
  }
  var sum = magicnumber.reduce((a,b)=>{return a+b},0);
  //Display array element
  document.getElementById("demo1").innerHTML = "Your data : " + magicnumber.join(', ');
  document.getElementById("sum").innerHTML = "The sum : " + sum;
}
&#13;
<div id="demo1"></div>
<div id="sum"></div>
&#13;
&#13;
&#13;