Sum values from an array of key-value pairs in JavaScript(从 JavaScript 中的键值对数组中求和值)
问题描述
我已经定义了一个名为 myData
的 JavaScript 变量,它是一个 new Array
,如下所示:
I have defined a JavaScript variables called myData
which is a new Array
like this:
var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0],
['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0],
['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);
我想知道是否可以对数组中找到的数值求和(例如 0+0+21+2+0 等),并且可能有一个变量,其结果可以在script 标签,因为我有 7 个此类数组对应于一周中的每一天.我想在此基础上进行比较.如果可能的话,那是这种行动的最首选方法吗?
I am wondering if it is possible to sum the number values found in the array (ex. 0+0+21+2+0 and so on) and have probably a variable with the result that I can use outside of the script tag because I have 7 of this kind of arrays corresponding for each of the day in the week. I want to make a comparison afterwards based on that. That is the most preferred method for this kind of actions if is possible?
推荐答案
试试下面的
var myData = [['2013-01-22', 0], ['2013-01-29', 1], ['2013-02-05', 21]];
var myTotal = 0; // Variable to hold your total
for(var i = 0, len = myData.length; i < len; i++) {
myTotal += myData[i][1]; // Iterate over your first array and then grab the second element add the values up
}
document.write(myTotal); // 22 in this instance
这篇关于从 JavaScript 中的键值对数组中求和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 JavaScript 中的键值对数组中求和值


- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01