Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 减少噪音';js中的t和数组数_Javascript_Arrays_Numbers_Reduce - Fatal编程技术网

Javascript 减少噪音';js中的t和数组数

Javascript 减少噪音';js中的t和数组数,javascript,arrays,numbers,reduce,Javascript,Arrays,Numbers,Reduce,我有一个数组,可以得到每种产品的数量,我想对它们的数量求和,但当我使用reduce时,它只会根据图片将数组中的数字放在红色购物按钮中,彼此相邻 这是我的代码: function updateTotal() { let total = 0; let arr = []; const items = document.querySelectorAll(".prodItem"); for (i = 0; i < items.length; i++) {

我有一个数组,可以得到每种产品的数量,我想对它们的数量求和,但当我使用reduce时,它只会根据图片将数组中的数字放在红色购物按钮中,彼此相邻

这是我的代码:

function updateTotal() {
  let total = 0;
  let arr = [];
  const items = document.querySelectorAll(".prodItem");
  for (i = 0; i < items.length; i++) {
    priceAmount = items[i].querySelectorAll(".prodPrice")[0];
    productQuantity = items[i].querySelectorAll(".num")[0];
    const quantity = productQuantity.value;
    const priceContent = priceAmount.innerText;
    const price = priceContent.replace("$", "");
    total += price * quantity;
    document.querySelector(".total-amount").innerText = "$" + total;
    arr.push(quantity);
  }

  counter.innerText = arr.reduce(
    (accumulator, currentValue) => accumulator + currentValue
  );
}
函数updateTotal(){
设total=0;
设arr=[];
const items=document.queryselectoral(“.prodItem”);
对于(i=0;i累加器+currentValue
);
}

这是否回答了您的问题?您的数字数组是字符串数组。在添加值之前,需要将这些字符串转换为数字。(在
中减少
或将它们添加到数组中时。)(我个人只需将
productQuantity.value
更改为
Number(productQuantity.value)