首页 > 解决方案 > 如何将数组的每个元素与字符串连接起来

问题描述

在 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 + "$");

但不成功。购物车上只显示浮点数,没有美元符号

我无法弄清楚我在哪里犯了错误。这种方法有什么问题吗:items.forEach((each) => each = "$" + each.textContext);

标签: javascript

解决方案


each您正在使用此覆盖丢失对原始对象的引用

items.forEach((each) => each = "$"+ each.textContext);

您应该尝试使用标准 for 循环

for (let i = 0; i < items.length; i++) {
    items[i] = "$"+ items[i].textContext;
}

推荐阅读