代码之家  ›  专栏  ›  技术社区  ›  slartidan

如何检测一个数组被另一个相同的数组替换?

  •  1
  • slartidan  · 技术社区  · 6 年前

    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"]
    

    即使新旧数组的内容相同,如何检测存储在变量中的数组是否已更改?

    2 回复  |  直到 6 年前
        1
  •  3
  •   ChrisG    6 年前

    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

    请注意 backup

        2
  •  5
  •   mpm    6 年前

    你可以用代理

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

    (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