1

In my code, I have a variable containing an array. I want to debug manipulations of that variable. I do not mind if the contents of the array are changing, but I have to see how often and when the array itself changes.

An example:

window.myarray = []
console.log(window.myarray); // outputs: []

window.myarray.push("bla"); // an irrelevant manipulation
console.log(window.myarray); // outputs: ["bla"]

window.myarray = ["bla"]; // a change of the array's identity!
console.log(window.myarray); // still outputs: ["bla"]

How can I detect, that the array that is stored in a variable has changed, even if the content of the old and new arrays are the same?

slartidan
  • 20,403
  • 15
  • 83
  • 131
  • Store a temporary reference to `window.myarray`'s state you want to detect it changing from. E.g `tmp = window.myarray` – mTv Sep 10 '18 at 11:05

2 Answers2

5

You could use proxies

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

Or you can define a property on window

(function() {
  let _myArray;
  Object.defineProperty(window, "myArray", {
    set(value) {
      _myArray = value;
      console.log('changed', value);
    },
    get() {
      return _myArray
    }
  })
}())

window.myArray = [];

window.myArray = ['bar'];

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

mpm
  • 20,148
  • 7
  • 50
  • 55
3

You check the identity like this:

window.myarray = []
var backup = window.myarray;

window.myarray.push("bla"); // an irrelevant manipulation
console.log(backup === window.myarray); // true

window.myarray = ["bla"]; // a change of the array's identity!
console.log(backup === window.myarray); // false

Note that backup isn't an actual copy, just a reference to the same in-memory object.

  • This is already helpful, but I would prefer to be able to compare it in the console log. – slartidan Sep 10 '18 at 11:07
  • @slartidan I don't understand what you mean by that, at all. –  Sep 10 '18 at 11:07
  • I would like to output something in the console log, that uniquely identifies an instance of an array. So that I can check afterwards if two logged arrays are identical or not. – slartidan Sep 10 '18 at 11:09
  • @slartidan I see; according to [this](https://stackoverflow.com/questions/50530936/is-there-any-method-to-check-memory-address-of-javascript-variable) there's no way to grab the memory address like for instance Java prints as default `toString()`. –  Sep 10 '18 at 11:26