如何检查是否在JavaScript中修改了typedArray?

时间:2019-04-25 13:38:18

标签: javascript

在我的情况下,有一个名为caculateTypedArray()的函数,经常调用。

function caculateTypedArray(array){
    if (array.isModified){
        // Goto A
    }else{
        // Goto B
    }
}

我想检查是否首先修改了typedArray参数。

例如:

function caculateTypedArray(array){
    if (array.isModified){
        // Goto A
    }else{
        // Goto B
    }
}

var f32Arr = new Float32Array([1, 2, 3]);
caculateTypedArray(f32Arr); //Goto B

f32Arr[0] = 2;
caculateTypedArray(f32Arr); //Goto A
//Or other form of modification
f32Arr.set([4, 5], 1); //Goto A

任何建议都值得赞赏!

1 个答案:

答案 0 :(得分:0)

  1. ES6:代理
var array = ["a", "b", "c", "d"];

var proxy = new Proxy( array , {
  apply: function(target, thisArg, argumentsList) { 
    // handle your event management here 
    return thisArg[target].apply(this, argumentList);
  },

  deleteProperty: function(target, property) {},
  set: function(target, property, value, receiver) {}  
});

// now just use 
proxy[0]; // to trigger apply
  1. ES5:定义属性
Object.defineProperty(myArray, "push", {
  enumerable: false, // false for...in
  writable: false, // Array.push = overwrite?
  value: function (...args)
    {
        let result = Array.prototype.push.apply(this, args); // Original push() 

        // handle your event management here 

        return result; // Original push() implementation
    }
});