Is there a way to get a get/set behaviour on an array? I imagine something like this:
var arr = [\'one\', \'two\', \'three\'];
var _arr = new Array();
for (
This answer is just an extension to the solution based on Proxy. See the solution with proxy, in that only get is mentioned but we can also use set as I am showing here.
Notice: 3rd argument in set can carry the value...
The code is self explanatory.
var _arr = ['one', 'two', 'three'];
var accessCount = 0;
function doSomething() {
accessCount++;
}
var arr = new Proxy(_arr, {
get: function(target, name) {
doSomething();
return target[name];
},
set: function(target, name, val) { doSomething(); target[name] = val; }
});
function print(value) {
document.querySelector('pre').textContent += value + '\n';
}
print(accessCount); // 0
print(arr[0]); // 'one'
print(accessCount); // 1
arr[1] = 10;
print(accessCount); // 2
print(arr[1]); // 10