summing numbers stored in an array in JavaScript(在 JavaScript 中对存储在数组中的数字求和)
问题描述
我想对存储在 JavaScript 对象中的数字列表求和.使用以下代码创建和更新对象:
I want to sum a list of numbers stored in a JavaScript object. The object is created and updated using this code:
var myscore = $('input[name="Points1"]').val();
scorelist = JSON.parse(localStorage.getItem(playerName + 'scorelist') || '[]');
scorelist.push(myscore);
localStorage.setItem(playerName + 'scorelist', JSON.stringify(scorelist));
$('div.scorecolumn', column).html("Score: <br>" + scorelist.join('<br>') + "<br>");
基本上,我获取当时列中的任何内容,对其进行解析,添加 myscore
,将其字符串化,将每个元素与 <br>
连接并编写列表到分数列.数字列表保存为对象.我的目标是在任何给定时间汇总对象中的所有数字.
Basically I take whatever is in the column at the time, parse it, add myscore
, stringify it, join each element with a <br>
and write the list to the scorecolumn. The list of numbers is saved as an object. My goal is to sum up all the numbers in the object at any given time.
这个脚本在一个函数内部,它传入了一堆参数,这就是为什么有些变量在这里看起来没有定义.
This script is inside of a function that passes in a bunch of parameters which is why some variables look undefined here.
任何帮助将不胜感激!谢谢
Any help would be greatly appreciated! Thanks
更新:
var nicTotalScore = nicScoreList.reduce(function(score, total) {
return total + score;
}, 0);
console.log(nicTotalScore); //12120
console.log(nicScoreList); //["12", "12"]
更新:如果提交时分数字段为空,则为空字符串"而不是分数.当 reduce 方法通过数组时,这将注册为 0.这不会影响总分,但是比如说,我想然后找到平均分,它就把它扔掉了.有什么想法吗?谢谢
UPDATE: If the score field is left blank when submitted, an empty string " " instead of a score. this is registering as a 0 when the reduce method goes through the array. This doesnt affect the total, but say, for example, i wanted to then find the average score, it throws it off. any ideas there? thanks
推荐答案
如果你 push()
到 scorelist
,我很可能会说这可能是一个 <代码>数组.
If you push()
to scorelist
, I'd be tempted to say it's likely an Array
.
你可以使用 reduce()
.
var total = scorelist.reduce(function(total, score) {
return total + +score;
}, 0);
这篇关于在 JavaScript 中对存储在数组中的数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 JavaScript 中对存储在数组中的数字求和


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01