Extending Array functionality safely in Javascript

So I’m using AngularJS to create some tables of data and want to have a simple way to sum the columns at the bottom. I could write a function and attach to $scope however I’d like to be able to use this with a minimum of typing and have it the same in the templates as in Javascript. A good situation to extend Array.prototype.

Array.prototype.sum_col = function(col) {
        var t = 0; 
        for( var i = 0; i < this.length; i++ )
            t += parseFloat( this[i][col] );
            
        return t;
    };

Nice and easy. However then I noticed that certain pages of my Angular app didn't load with a very random error. After some debugging in the chrome JS browser it came down to the fact that whilst the above 3-statement for loop works fine, if I now do for( var i in array ) it also includes the sum_col function. D'oh. So after some research on stackoverflow I figured out the correct way to add stuff to Array.prototype which should probably be done by default whenever you want to:

Object.defineProperty( Array.prototype, "sum_col", {
    enumerable: false,
    value: function(col) {
        var t = 0; 
        for( var i = 0; i < this.length; i++ )
            t += parseFloat( this[i][col] );
            
        return t;
    }       
});         

Leave a Reply

Your email address will not be published. Required fields are marked *