gpt4 book ai didi

javascript - 如何在数组中添加数字,并在向数组添加更多数字时重新计算并添加数字?

转载 作者:行者123 更新时间:2023-12-02 16:54:07 25 4
gpt4 key购买 nike

我正在尝试在数组中添加数字并使用添加的数字更新 DOM。然后,当更多数字添加到数组中时,当再次运行加法函数时,会重新计算数组,并使用数组中数字相加的值更新 DOM。

这是一个 fiddle :http://jsfiddle.net/scu67aou/2/

目前,它只显示数组中的最后一个数字,而不是添加数组中的内容。感谢您的帮助。

JavaScript:

var numb = [];
var total = '';

$('.new').on('click', function(){
var infoStuff = $('.to-add input').val();
$('.added').append('<div class="test">'+ infoStuff + '</div>');
numb.push(infoStuff);
});

$('.button').on('click', function(){
for(var i=0; i < numb.length; i++){
total = Number(numb[i]);
}
$('.total').html(total);
});

最佳答案

您需要将新值添加到循环内的total,而不是为其分配新值。另外,将 total 声明为局部变量 - 否则新数字将添加到先前计算的总计中:

$('.button').on('click', function () {
var total=0; // local variable, starts with 0 every time
for (var i = 0; i < numb.length; i++) {
total += Number(numb[i]); // add the number to existing total
}
$('.total').html(total);
});

Updated Fiddle

关于javascript - 如何在数组中添加数字,并在向数组添加更多数字时重新计算并添加数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26311446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com