1

For a school project I need to make a game in C. However, since I'm much more fond with javascript + js can give a easy visual implementation, I decided to write my game in js before in c, to get my structure right. That's why my code's so weirdly looped.

Now, the issue is that I have a switches[] array that has the switches being pressed (1/0). I want to compare this to another array, oldArray[]. Now, when comparing, they are both ALWAYS the same for some reason, and I just can't find it. Here's a full sample on jsfiddle.net. The issue is in the memory() function. This line isn't working properly:

if (switches[i] == 1 && oldArray[i] == 0 && guessedArray[i] == 8 && i != oldtouch) {...}

because switches[] always seems to be equal to oldArray[].

In the fiddle, press Start and check the consle output after clicking some buttons.

jdepypere
  • 3,453
  • 6
  • 54
  • 84

1 Answers1

2

They are equal, because when the assignment statement oldArray = switches is executed, both variables point to the same underlying object in memory.

To copy all the values from one array to the other, without having them point to the same object, do oldArray = switches.slice(0)

See this for further discussion: Copying array by value in JavaScript

Community
  • 1
  • 1
Shaun
  • 2,446
  • 19
  • 33
  • Oh I see.. How do I only make the values equal then? So I only set all the values from `switches` to `oldArray` once, and when `switches` changes `oldArray` doesn't? – jdepypere Apr 27 '13 at 01:19
  • 1
    I edited the answer to add info on how to achieve your desired outcome. – Shaun Apr 27 '13 at 01:22