0

It's been a while since I've touched JavaScript, but something has got me flummoxed, simple I just know I should know it, but it's causing me a massive headache for the past hour!

Scenario;

Mop = {
  els : [],
  pool : [],
  generate : function(){
    for (var i=0; i<Mop.els.length; i++){
      Mop.pool.push(i)
    }
  },
  oneAtime : {
    p : Mop.pool,
    runit : function(){
      timerID = window.setTimeout(function(){
        Mop.show()
      });
    }
  },
  show : function(){
     var p = Mop.oneAtime.p;
     var r = Math.floor(p.length * Math.random());
     p.splice(r,1);
  },
  init : function(){
    Mop.els = $(".cells");
    Mop.generate();
    Mop.oneAtime();
  }
}
Mop.init()

A long winded way to say it's a problem with variable assigning. But I thought I'd show the context.

In short, invoking Mop.show() affects both the arrays Mop.pool, and Mop.oneAtime.p, even though the latter was assigned Mop.pool value, and Mop.pool is not touched again. Mop.pool must remain un-altered.

I can hear someone laughing at how easy this must be - but I just cannot work out why both arrays are affected by the splice() method! Scope, closure, something like that I bet, I've tried all I can think of...

Filburt
  • 17,626
  • 12
  • 64
  • 115
BusterLuke
  • 298
  • 2
  • 4
  • 11
  • JavaScript doesn't create a copy of the array when you assign it to a variable. `p` and `Mop.oneAtime.p` refer to the same array. – Felix Kling Feb 17 '14 at 23:57
  • possible duplicate of [Copying array by value in javascript](http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript) – Felix Kling Feb 17 '14 at 23:58
  • 1
    Also I assume that your actual code is slightly different because in your example, `p : Mop.pool,` will throw a runtime error (`Moo` doesn't have a value at that moment). – Felix Kling Feb 18 '14 at 00:00
  • I extracted meaningful bits of a much longer bit of code. I think the key question is how do I assign a variable (array) to another variable and alter it, with the original being affected? I've googled away but don't know really how to phrase it I guess! – BusterLuke Feb 18 '14 at 00:04
  • 1
    I think you mean "without". And you do this by *cloning* or *copying* the array. Just as shown in the linked question. – Felix Kling Feb 18 '14 at 00:05

0 Answers0