在 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 方法对总数组中的所有价格元素求和后,我尝试将“$”字符串与“cart-prize”的每个文本内容相连接:
items.forEach((each) => each = each.textContext + "$");
但没有成功,购物车上只显示 float ,没有美元符号
我不知道我在哪里犯了错误。这种方法有问题吗:items.forEach((each) => each = "$" + each.textContext);
最佳答案
你失去了对原始 each
对象的引用,这个覆盖
items.forEach((each) => each = "$"+ each.textContext);
你应该尝试使用标准的 for 循环
for (let i = 0; i < items.length; i++) {
items[i] = "$"+ items[i].textContext;
}
关于javascript - 如何用字符串连接数组的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54311063/