Need help, there is a function

function showMiniCart(){ //показываю содержимое корзины var out =''; for (var key in cart) { out += Object.keys(cart).reduce((total, key) => total += cart[key], 0); } $('#mini-cart').html(out); } 

The problem is that it doesn’t bring out quite right, that’s what I wanted, namely, the basket will fall: If I add 1 product, everything adds up normally, but when you add 2 products, the result is added and displayed side by side again.

Example: 1 item - output 1, 2 item - output 22, 3 item - displays 333.

  • var out = 0; (2 characters needed ...) - Igor
  • var out = 0; I tried it, it does not help at all. Considers it now strange at all. Can it even be necessary to build a function to add goods? - Ivan

1 answer 1

Remove + in line

 for (var key in cart) { out = Object.keys(cart).reduce((total, key) => total += cart[key], 0); } 

you concatenate strings, and based on the task, you should get a new value

  • + Here is a pancake ... a long working day makes itself felt. - Ivan
  • @Ivan if my message helped you, then you can mark it as the correct answer) - Taarim
  • Everything is good, but I found an error) in ie Object Object.keys is not supported, will you not advise how to solve it differently then?) - Ivan
  • @Ivan if you need a quantity of products in the cart, try using Object.length. although it seems to me a good decision would be to make it like this $ ('# mini-cart'). html (cart.length); - as I understand it in the cart are the goods in the form of objects - Taarim