Intercepting JavaScript array accessor

Viewed 2377

I would like to associate some side effect with every array accessor like a[i]. For example, if the side effect is writing a message to the console, the following program:

var array = [1, 2, 3]
var total = 0;
for (var i in array) {
  total += array[i]
}
console.log(total);
should return the output like:

1 // access a[0]
2 // access a[1]
3 // access a[2]
6 // print original total

In case I was interested in intercepting an array method push, I'd use the technique from this blog post and provided an interceptor:

var _push = Array.prototype.push;
Array.prototype.push = function( item ) {
    console.log( 'pushing ', item, ' into ', this );
    _push.apply( this, arguments );
}

Is it possible apply the same trick to an array accessor? Or what would be a better solution for this problem? One important note is that I don't want to modify the original code of the program. Therefore, using JS proxies to intercept getters and setters doesn't seem te be a valid option for my problem.

One particular side effect, I want to introduce is raising an exception in case the accessed value is undefined (some variation of the index out of bounds exception for JS arrays.) I would check if the currently accessing value is equal to undefined, and throw an exception, in that case, otherwise just return the original value.

2 Answers
Related