繁体   English   中英

无法添加数组元素

[英]Unable to add array elements

我正在尝试使购物车成为一种练习,但是我无法将所选产品的价格加在一起。

JS:

var productPrice = document.getElementById("productPrice");

var totalPrice = document.getElementById("totalPrice");

var addAlert = document.getElementById("addAlert");

var arr = [];

function addToCart() { // onclick Event to add and show the price
 arr.push(productPrice.innerHTML);
 function getSum(total, num) {
 return total + num;
}
var tempTotal = arr.reduce(getSum);
totalPrice.innerHTML = tempTotal;

}

因此,如果价格为2000,并且将其相乘多次,则应输出2000 + 2000 + 2000 = 6000,但现在仅输出200020002000。

我该如何解决?

您需要将productPrice.innerHTML转换为数字。

function addToCart() { // onclick Event to add and show the price
  arr.push(Number(productPrice.innerHTML));
  function getSum(total, num) {
    return total + num;
  }
  var tempTotal = arr.reduce(getSum);
  totalPrice.innerHTML = tempTotal;
}

问题是您要附加字符串值,因此您需要将其转换为数字值,并用简短的方式

//make use of text instead of html 
const number:Number = +productPrice.innerText;

所以在你的代码中你必须这样做

let arr:Number = [];
//define array with number type so you cannot add other then number 
arr.push(+productPrice.innerText);
//addeing number to array 

@ Tankit88 ,您将需要使用parseInt()将数组中的字符串形式的数字转换为数字,即'2000' => 2000 ,这在以下代码之后的Node REPL上已执行的代码中很清楚。

var productPrice = document.getElementById("productPrice");
var totalPrice = document.getElementById("totalPrice");
var addAlert = document.getElementById("addAlert");

var arr = [];

function addToCart() { // onclick Event to add and show the price
    arr.push(parseInt(productPrice.innerHTML));

    function getSum(total, num) {
        return total + num;
    }

    var tempTotal = arr.reduce(getSum);
    totalPrice.innerHTML = tempTotal;
}

最后,看看下面在Node REPL上执行的代码,这些代码阐明了上面代码的逻辑。

> arr = ['2000', '2000', '2000']
[ '2000', '2000', '2000' ]
>
> function getSum(total, num) {
...  return total + num;
... }
undefined
>
> var tempTotal = arr.reduce(getSum);
undefined
>
> tempTotal
'200020002000'
>
> // A little change to solve above problem
undefined
> function getSum(total, num) {
...  return parseInt(total) + parseInt(num);
... }
undefined
>
> var tempTotal = arr.reduce(getSum);
undefined
>
> tempTotal
6000
>

谢谢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM