[英]Get the sum of values in array
我有这个示例代码:
<table>
<tr>
<td class="price">1</td>
</tr>
<tr>
<td class="price">4</td>
</tr>
<tr>
<td class="price">6</td>
</tr>
</table>
<p id="setTotal"> </p>
我想在“价格”类下获得这些值的总和,但是我的输出类似于:
1 4 6 Sum为0 [object HTMLTableCellElement] [object HTMLTableCellElement] [object HTMLTableCellElement]。
我的JavaScript代码是:
var arr = [];
var totalPrice = 0;
var i;
$("td.price").each(function(){
arr.push($(this).text());
totalPrice += this;
document.getElementById("setTotal").innerHTML = "Sum is "+totalPrice+ ".";
});
您需要从td获取文本并将其解析为数字。
小提琴: http : //jsfiddle.net/4rwbyx3n/
var arr = [];
var totalPrice = 0;
var i;
$("td.price").each(function(){
arr.push($(this).text());
var price = $(this).text();
totalPrice += Number(price);
document.getElementById("setTotal").innerHTML = "Sum is "+totalPrice+ ".";
});
你有两个问题:
totalPrice
通过this
,这是一个HTML元素。 以下是更改,以及一些小的改进/建议:
var totalPrice = 0;
$("td.price").each(function(i, td) {
totalPrice += parseInt($(td).text());
});
$('#setTotal').html("Sum is " + totalPrice + ".");
尝试:
$("td.price").each(function(){
arr.push($(this).text());
totalPrice += (+$(this).text());
document.getElementById("setTotal").innerHTML = "Sum is "+totalPrice+ ".";
});
您之前的结果的原因是您连接HTML
元素,而不是其中的文本。
这样的事情:
使用javascript的array.map,您可以将某个数组转换为其他内容。
在这种情况下,将html元素数组转换为数字数组。
使用reduceRight对结果进行简单的add函数作为参数,数组的每个元素被逐个累加和求和。
我们需要将它包装在jQuery.makeArray中,因为jQuery $(selector).map将返回一个jQuery对象,我们想要一个原生的javascript数组。
var sum = jQuery.makeArray($("td.price").map(function(idx, num) {
return parseInt($(num).text());
}).reduceRight(function(a,b){return a+b;}));
接着
document.getElementById("setTotal").innerHTML = "Sum is "+sum+ ".";
或者使用jquery
$("#setTotal").text("Sum is " + sum + ".");
你必须parseFloat
元素的文本。 你还需要jquery
来处理.each()
函数
var totalPrice = 0; $("td.price").each(function(){ totalPrice += parseFloat($(this).text()); document.getElementById("setTotal").innerHTML = "Sum is "+totalPrice+ "."; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td class="price">1</td> </tr> <tr> <td class="price">4</td> </tr> <tr> <td class="price">6</td> </tr> </table> <p id="setTotal"> </p>
你正在推动html元素/对象到你的总和,不知道为什么,并且因为你已经在使用jQuery,所以不需要本机JS选择器和方法:
var totalPrice = 0;
$("td.price").each(function(){
totalPrice +=parseInt($(this).text());
});
$("#setTotal").html("Sum is "+totalPrice+ ".");
此外,您可以移动显示每个()循环的价格,不需要在循环内更新...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.