user757289
user757289

Reputation:

Array values not being changed by method

not a js expert so this might be a stupid question but...

Why does the log show that the array has changed? I was expecting the array still to be a [0,0] since the method is invoked after the console.log. Also, if I try to replace the whole array like this:

this.my_array = [1,0];

the log will still show [0,0], which is something that makes more sense to me. What's going on?

function Y() {        
  this.my_array = [0,0];            
  this.changeIt = function() {
    this.my_array[0] = 1;
  };
}

var z = new Y;
console.log(z.my_array);
z.changeIt();

Upvotes: 0

Views: 114

Answers (2)

Lukas_Skywalker
Lukas_Skywalker

Reputation: 2070

It works for me: http://jsfiddle.net/LyhgW/

Edit: The fact that i'm using alert makes this code work. This works around Chrome's live-feature in the console and displays a snapshot instead.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074485

In some browsers (Chrome, for instance) console.log displays a live, interactive display of your array, not a point-in-time snapshot. So if you're looking at the console after this runs, it's been updated because of the change. Chrome also does slightly different things when you use console.log interactively in the console panel than when you use it from within a script.

You'll see what you're expecting if you display a string instead:

var z = new Y;
console.log(z.my_array.join(", "));
z.changeIt();

That shows the point-in-time snapshot you're expecting.

Upvotes: 7

Related Questions