为什么不是't单击事件中返回的数组的总和
Why isn't the sum of my array being returned on the click event?
我正在处理一个项目,用户将数字添加到数组中,然后在单击事件中返回这些值的总和。但是,对于我的"total"变量,"total(总计)"按钮只返回0。只是无法解决我根据这里看到的内容设置总变量的问题:如何使用javascript添加数组元素值?
var times = [];
var total = 0;
for (var i = 0; i < times.length; i++) {
total += +times[i];
}
document.getElementById("add").onclick = function () {
times.push(1);
};
document.getElementById("total").onclick = function () {
alert(times + " adds up to " + total);
};
这是我的小提琴
JavaScript(在浏览器中)按顺序运行。当浏览器遇到以下代码块时:
for (var i = 0; i < times.length; i++) {
total += +times[i];
}
它立即运行。您的单击处理程序document.getElementById("total").onclick
需要在每次单击时重新计算总数。我建议使用一个函数来做到这一点:
var times = [];
var getTotal = function (arr) {
return arr.reduce(function (currentSum, next) { return currentSum + next });
}
document.getElementById("add").onclick = function () {
times.push(1);
};
document.getElementById("startsequence").onclick = function () {
alert(times + " adds up to " + getTotal(times));
};
<button id="add">add</button>
<button id="startsequence">total</button>
Array.reduce
只是for循环的一个更高级的版本。你可以在这里阅读文档。
您需要将计算总数的代码放入total
onclick
函数中。
document.getElementById("startsequence").onclick = function () {
total = 0;
for (var i = 0; i < times.length; i++) {
total += +times[i];
}
alert(times + " adds up to " + total);
};
新jsfiddle:https://jsfiddle.net/6sp29efd/3/
执行计数时,数组中没有任何内容。
您应该在total
按钮的点击处理程序中执行计数
查看更新的小提琴
顺便说一句,你可以用reduce:以一种更性感的方式进行计算
document.getElementById("startsequence").onclick = function () {
var total = times.reduce(function (a, b) {
return a + b;
});
alert(times + " adds up to " + total);
};
这是因为计算数组中元素的for循环仅在程序开始时执行,此时"times"数组为空。
当您在DOM上实际请求点击"start-sequence"元素的总数时,您必须计算"times"数组的长度。
var times = [];
function calcTotal () {
var total = 0;
for (var i = 0; i < times.length; i++) {
total += +times[i];
}
return total;
}
document.getElementById("add").onclick = function () {
times.push(1);
};
document.getElementById("startsequence").onclick = function () {
alert(times + " adds up to " + calcTotal());
};
我已经将for循环封装在一个函数中,当您请求total时会调用该函数。这样你就可以在需要的时候准确地计算数组的长度
https://jsfiddle.net/ncqyLpr1/
在创建任何元素之前计算总和。times为空,有0个元素,长度为0。您用0初始化i,0已经不小于times.length,total的值保持为0。你需要做这样的事情:
var times = [];
var total = 0;
document.getElementById("add").onclick = function () {
times.push(1);
};
document.getElementById("total").onclick = function () {
total = 0;
for (var i = 0; i < times.length; i++) {
total += +times[i];
}
alert(times + " adds up to " + total);
};
- Regex提取URL返回数组的一部分;未定义”;
- 为循环嵌套的Javascript未按预期返回数组
- 从函数中的函数返回数组时出错
- JSON返回数组的奇怪结果
- 如何从NodeJS中的模块返回数组
- 在JS中返回数组的大整数运算
- 从Nodejs中的函数返回数组,并将其发送到ejs视图
- 从函数返回数组
- undercore返回数组中对象的indes,其中单词存在于对象中的句子中
- Yui Get 复选框返回数组而不是布尔值
- 从异步调用返回数组,然后为数组的每个元素返回其他异步调用
- JavaScript闭包和返回数组元素
- 按流星空格键模板中的索引返回数组项
- 从多个文件中推送文本的函数(使用html5文件读取器上传)返回数组
- 我想返回数组
- PHP和Ajax在回调和返回数组中使用foreach循环
- Javascript-如何通过以字符串作为参数返回数组
- 从JSON调用SQL返回数组时出现问题
- Jasmine spyOn使用伪造的返回数组测试功能
- 无法从从sql数据库读取的javascript函数中获取返回数组