在JavaScript中汇总存储在数组中的数字

编程入门 行业动态 更新时间:2024-10-25 08:20:12
本文介绍了在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> 连接每个元素,并将列表写入scorecolumn。数字列表保存为对象。我的目标是在任何给定的时间总结对象中的所有数字。

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()到得分列表,我很想说它可能是数组。

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中汇总存储在数组中的数字

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

发布评论

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

>www.elefans.com

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