我试图得到循环内部每个数组的和。我现在的代码是这样的
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>问题是--它没有显示元素之和。也许我还需要一个数组的循环内部的循环呢?
发布于 2020-06-23 12:09:11
在获得完整的解决方案之前先做一个小介绍:
求和
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-*属性对整数is,并使用类似的代码,如下所示:
$("[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>
https://stackoverflow.com/questions/62534299
复制相似问题