无法添加数组元素

时间:2018-05-22 05:51:11

标签: javascript

我正在尝试将购物车作为练习,但有些我无法将所选产品的价格加在一起。

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。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

您需要将$professionals = DB::table('member_professional as mp') ->select('mp.member_id_fk', 'mp.col1', 'mp.col2', 'mp.col3', DB::raw("(GROUP_CONCAT(DISTINCT p.picture_path SEPARATOR ',')) as 'photos'")) ->join('member as m','mp.member_id_fk','=','m.member_id') ->join('photos as p','p.member_fk','=','m.member_id') ->leftjoin('locations','m.city','=','locations.location_id'); if ($professionals_type != '') { $professionals = $professionals->where('mp.biz_category','=',$professionals_type); } if ($location != '') { $professionals = $professionals->where('m.city','=',$location); } $professionals = $professionals->where('m.member_type','=',2) ->groupBy('mp.member_id_fk', 'mp.col1', 'mp.col2', 'mp.col3') ->paginate(20); 转换为数字。

productPrice.innerHTML

答案 1 :(得分:0)

问题是你要附加字符串值,所以你需要将它转换为数字值并缩短方法来实现它

//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 

答案 2 :(得分:0)

@ Tankit88 ,您需要使用'2000' => 2000将数组中的字符串形式数字转换为数字parseInt(),这在节点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;
}

最后,看一下节点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
>

感谢。