将数组加在一起,显示和 [英] add array together, display sum

查看:73
本文介绍了将数组加在一起,显示和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是接受用户输入的数字,然后将这些数字相加并显示总和。

What i am trying to do is take the user input which is numbers then add those numbers together and display the sum.

我有一个数组,我有数组的总和。现在我只需要显示总和。看来我的循环正在输出数组中的所有数字。

I have an array, I have the sum of the array. Now I need to display only the sum. It seems my loop is outputting all the numbers in the array.

function hello(){


var arr = [];                               // define our array

for (var i = 0; i < 3; i++) {              // loop 10 times
  arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}

alert('Full array: ' + arr.join(', '));    // alert the result`

var total = 0;
for(i=0; i<arr.length; i++){
  var number = parseInt(arr[i], 10);
  total += number;
  console.log(total);

// gets the last element in arr[] array //does not give answer
var totalArr = arr[i][arr[i].length-1]; 
}

console.log(totalArr);


推荐答案

如果只需要最后的总输出那么您需要在循环后将总计记录到控制台。根据对您要做什么的了解,我认为需要执行以下操作……

Well if you want just the total output at the end then you need to log total to the console after the loop. Based on my understanding of what you want to do I think something like the following is all that's needed...

function hello() {
    var arr = [];

    for (var i = 0; i < 10; i++) {
        arr.push(prompt('Enter number' + (i+1)));
    }

    var total = 0;

    for(i=0; i<arr.length; i++) {
        var number = parseInt(arr[i], 10);
        total += number;
    }

    console.log(total);
}

这篇关于将数组加在一起,显示和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆