-1

I have an two arrays of products called cart and stock. Let's say there are 5 products a to e.

Stock might look like

stock[a] = 5, stock[b] = 5...

etc etc

and cart might look like

cart[a] = 2, cart[b] = 0...

I am trying to do something like

for (var product in cart){ if(cart[product] > 0){ cart[product] = stock[product] }

But stock[product] always returns 0. How can i make it so that I can use the same variable product to access products within both stock and cart?

I tried something like

for (var product in cart && var product in stock) 

but it doesnt work.

Is there any other alternative?

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
Steven Hsu
  • 183
  • 1
  • 3
  • 15
  • ”But stock[product] always returns 0” – how are you determining this? – Ry- Nov 15 '15 at 23:21
  • 1
    Can you post more of your code? You already can use `product` as a key in both `stock` and `cart`, so you must have another problem. Have you tried `console.log` on `stock` and `cart` to see if they contain what you think they do? – David Zorychta Nov 15 '15 at 23:22
  • http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea – Chris L Nov 15 '15 at 23:29
  • 1
    Instead of reusing your question and changing it to another one, you should just make a new question, it works out better for you because people tend to look at the newest questions. But above all this question is now completely confusing, nothing matches between the comments/answers and your question. – Sean_A91 Nov 16 '15 at 00:01
  • 1
    Uh, just don't make synchronous XMLHTTPRequests? They *do freeze* the browser, that's exactly why you shouldn't use them. – Bergi Nov 16 '15 at 00:23

1 Answers1

0

It's unclear as to whether or not you are iterating over an array or an object, but since your question says array, I will assume both cart and stock are arrays and a and b are numbers.

As Chris L mentioned, you probably shouldn't be using a for..in loop for arrays, so I would recommend just a normal for loop.

for (var i = 0; i < cart.length; i++) {
  if (cart[i] > 0) {
    cart[i] = stock[i];
  }
}

If you target IE9+, a forEach is a little cleaner, in my opinion.

cart.forEach(function (item, index) {
  if (item > 0) {
    cart[index] = stock[index];
  }
}

Side note: this code looks like it's re-assigning cart[i] if it's greater than 0 which seems very weird to me...

kmiyashiro
  • 2,249
  • 14
  • 15