在html中:<span class="cart-prize">30.00</span>
const total = [];
const items = document.querySelectorAll('.cart-prize'); //item price displaying on the cart when cart popups
items.forEach(function(item)
{
total.push(parseFloat(item.textContent)).toFixed(2);
});
const totalMoney = total.reduce((accumulator, EachArrayValue)
=> accumulator + EachArrayValue);
items.forEach((each) => each = "$"+ each.textContext);
document.getElementById("totalMoney").textContent =
"$"+totalMoney; //works ok
document.getElementById("itemTotal").textContent =
total.length + " items"; //works ok
在使用reduce方法对total数组中的所有价格元素求和后,我尝试将"$“字符串与”cart- in“的每个文本内容连接在一起:
items.forEach((each) => each = each.textContext + "$");
但不会在购物车上显示没有美元符号的succeed.Only浮点数
我不知道我在哪里弄错了。这个方法有什么问题吗:items.forEach((each) => each = "$" + each.textContext);
发布于 2019-01-22 15:13:08
使用此覆盖将丢失对原始each
对象的引用
items.forEach((each) => each = "$"+ each.textContext);
您应该尝试使用标准for循环
for (let i = 0; i < items.length; i++) {
items[i] = "$"+ items[i].textContext;
}
发布于 2019-01-22 15:29:18
使用items.forEach((each) => each = each.textContext + "$");
的问题是,它只在items
数组之间迭代,而没有创建新的数组。
您可以不使用forEach
,而是使用map
,它会创建一个新的数组,并再次向items
赋值,如下所示:
let items = [{textContent: "example1"}, {textContent: "example2"}];
items = items.map((object) => {
object.textContent = "$" + object.textContent;
return object;
});
console.log(items);
有关map
和foreach
之间差异的更多信息,请参阅find here。
发布于 2019-01-22 17:02:59
他/她的评论中的错误是正确的。您需要做的就是在forEach循环中使用each.textContent
而不是each
。
items.forEach((each) => each.textContent = "&"+each.textContent);
https://stackoverflow.com/questions/54311063
复制