You cannot override this accessory arrays. Here is an example:
Object.defineProperty(Array.prototype, 0, { get: function () { return "my get on 0"; } }); var a = [1,2,3]; console.log(a[0]);
But if you try to do the same with a property that does not actually exist in the array, you will achieve it:
Object.defineProperty(Array.prototype, 5, { get: function () { return "my get on 5"; } }); var a = [1,2,3]; console.log(a[5]);
What you can do is a small workaround for accessing elements using the get method of arrays.
Array.prototype.get = function(i) { console.log('my print'); console.log(this[i]); return "this is!"; }; var a = [1,2,3]; console.log(a.get(0));
So, back to your question, you could do something like push , but with get , avoiding the proxy:
Array.prototype.get = function (i) { console.log('Accessing element: ' + this[i]); console.log(this); return this[i]; }; var array = [1, 2, 3]; var total = 0;
Just to complete the answer, what you are trying to do can be done on one line using the reduce method of arrays:
var array = [1, 2, 3]; var result = array.reduce(function (accumulator, actual) { return accumulator + actual; }, 0); console.log(result);
I highly recommend that you avoid overriding these accessories. You will change the basis of the code so that outsiders can not understand what is happening without reading the entire code. In addition, you will lose many built-in useful methods. Hope this helps
ps following your edit, to check for undefined values โโand raise exceptions, you can add a check inside an override of the get method. But my suggestion is only to filter the array, determine the undefined values โโand get rid of them. Please note that I am using double equal. because undefined == null , but undefined !== null . This way you remove both undefined and null values. If you want to remove only undefined, change it to if (typeof element === 'undefined') .
So, something like this, using only one loop with the filter arrays method:
var data = [1, 2, undefined, 3, 4, undefined, 5]; data = data.filter(function( element, index ) {
source share