javascript - 如何将数组的每个元素与字符串连接起来
问题描述
在 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);
解决方案
each
您正在使用此覆盖丢失对原始对象的引用
items.forEach((each) => each = "$"+ each.textContext);
您应该尝试使用标准 for 循环
for (let i = 0; i < items.length; i++) {
items[i] = "$"+ items[i].textContext;
}
推荐阅读
- azure - 允许访问 Azure Web 应用的等效 Azure 服务
- continuous-integration - Gitlab CI/CD 部署到本地 Tomcat
- c# - 从另一个窗口更新主窗口列表
- redux - GraphQL 查询在突变后仅获取一次数据
- f# - c# 到 f# 当 3rd 方库想要一个 byref 作为输出参数时
- reactjs - 在某些操作(任何)之后,如何重新获取位于另一个页面上的组件中的查询,但只有当您转到此页面时?
- php - 为什么使用 LIKE %value% 给我的 php 页面一个 500 代码?
- node.js - 在服务器端保存用户会话,而不在 client.side 上保存任何内容
- python - 如何在以下代码中隐藏 ping 结果?
- javascript - 根据复选框添加数字