简体   繁体   English

试图将数组的元素添加到一起

[英]Trying to add elements of an array together

I am trying to get input into an array using a do while loop until the user enters a blank or 0 then am trying to add all the elements within that array together however it returns them in string form. 我试图使用do while循环输入数组,直到用户输入空格或0然后我尝试将该数组中的所有元素一起添加,但它以字符串形式返回它们。

I have tried using parseInt() in multiple places however it usually makes the code not work at all. 我尝试在多个地方使用parseInt() ,但它通常会使代码根本不起作用。

document.getElementById('while').addEventListener('click', stats);
document.getElementById('while').addEventListener('click', reduction);

var input_array = [];
var value = 0;

function stats() {
  do {
    var number = prompt('Enter a Number');
    var array = input_array.push(number);

    document.getElementById('out2').innerHTML = "[" + input_array + "]";
  } while (value != number);
}

function array_sum(total, num) {
  return total + num;
}

function reduction(item) {
  document.getElementById('out3').innerHTML = input_array.reduce(array_sum);
}

If you simply parseInt before you push the value to the array you would get numbers in the array and all works as expected: 如果您在将值推送到数组之前只是parseInt ,那么您将获得数组中的数字并且所有数据都按预期工作:

 let input_array = []; let value = 0 function stats() { do { var number = prompt('Enter a Number'); var array = input_array.push(parseInt(number)); // <-- parse here } while (value != number); } stats() // show the prompt etc function array_sum(total, num) { return total + num } console.log(input_array.reduce(array_sum)) 

I only posted the js part without the html just to give you an example that it works as expected. 我只发布了没有html的js部分,只是为了给你一个按预期工作的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM