将数组加在一起,显示和

编程入门 行业动态 更新时间:2024-10-28 00:14:04
本文介绍了将数组加在一起,显示和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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); }

更多推荐

将数组加在一起,显示和

本文发布于:2023-10-19 20:35:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508697.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   加在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!