我正在尝试获取 for 循环内每个数组的总和。 我现在的代码是这样的
for (var i = 1; i < 6; i++) {
(function(i) {
if ($(".brand_name-"+i).length > 0 ) {
Array_new = parseInt ($(".price-" + i).text());
someArray = $.trim (Array_new);
var total = 0;
for (var k = 0; k < someArray.length; k++) {
total += someArray[k] << 0;
}
console.log(total);
}
元素的 HTML 版本是
<strong class="product_price_send price-3">88.87</strong>
<strong class="product_price_send price-5">8.78</strong>
<strong class="product_price_send price-5">48.78</strong>
问题是 - 它没有显示元素的总和。也许我需要在数组的 for 循环内再添加一个 for 循环?
最佳答案
获得完整解决方案之前的一个小介绍:
总计
const ELS_price = document.querySelectorAll(".product_price_send");
// const ELS_prod_price = $(".product_price_send").get(); // if you use jQuery
const sum = [...ELS_price ].reduce((tot, el) => {
tot += Number(el.textContent.trim());
return tot;
}, 0);
console.log(sum)
<strong class="product_price_send price-3">88.87</strong>
<strong class="product_price_send price-5">8.78</strong>
<strong class="product_price_send price-5">48.78</strong>
按 data-* 属性求和配对
针对您的具体问题或通过某个整数后缀将品牌与价格配对。
您能做的最好的事情是使用 data-*
属性对整数 ID 进行配对,并使用与上面类似的代码:
$("[data-brand]").each(function() {
const id = $(this).data("brand");
const ELS_price = document.querySelectorAll(`[data-price="${id}"]`);
const sum = [...ELS_price].reduce((tot, el) => {
tot += Number(el.textContent.trim());
return tot;
}, 0);
console.log(`${this.textContent} Sum: ${sum.toFixed(2)}£`)
});
<div data-brand="3">Foobar</div>
<div data-brand="5">Loremis</div>
<strong class="product_price_send" data-price="3">88.87</strong>
<strong class="product_price_send" data-price="5">8.78</strong>
<strong class="product_price_send" data-price="5">48.78</strong>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
关于javascript - for循环内数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62534299/