Get all values ​​of a variable using JS

So, in my code js, I have a global variable that changes its value several times, for example

var x = 0;
...
x = 10;
...
x = 5;

Is it possible to get a “history” xwithout saving its value in other variables? For example, is there any function to detect that at some point in time xit was 10?

+4
source share
4 answers

No, after assigning a variable to a variable, this variable will be overwritten. It is not saved anywhere. (If it were, it would be a nightmare for managing memory.)

You can create an object property that has a history if you want using the setter function; example:

var obj = {
  _fooValue: undefined,
  fooHistory: [],
  set foo(value) {
    this.fooHistory.push(this._fooValue);
    this._fooValue = value;
  },
  get foo() {
    return this._fooValue;
  }
};

obj.foo = 0;
obj.foo = 5;
obj.foo = 42;
console.log(obj.fooHistory);
Hide result

, , , , . , . , , :

var obj = (function() {
  // These two vars are entirely private to the object
  var fooHistory = [];
  var fooValue;
  
  // The object we'll assign to `obj`
  return {
    set foo(value) {
      fooHistory.push(fooValue);
      fooValue = value;
    },
    get foo() {
      return fooValue;
    },
    get fooHistory() {
      // Being really defensive and returning
      // a copy
      return fooHistory.slice(0);
    }
  }
})();

obj.foo = 0;
obj.foo = 5;
obj.foo = 42;
console.log(obj.fooHistory);
Hide result
+9

array unshift . :

var x = [];
...
x.unshift(10);
...
x.unshift(5);

var currentX = x[0];
var allValues = x;
+1

, . Time Traveling Microsoft Edge. .

0

JS, , , x ( Integer ), . , , .

, , . , - . , , , .

0

Source: https://habr.com/ru/post/1668235/


All Articles