Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending Array prototype in JavaScript [duplicate]

Tags:

javascript

I often found myself wanting to do certain operations for all the items in an array and I wished that JavaScript had something like C#'s LINQ. So, to that end, I whipped up some extensions of the Array prototype:

var data = [1, 2, 3];
Array.prototype.sum = function () {
    var total = 0;
    for (var i = 0; i < this.length; i++) {
        total += this[i];
    }
    return total;
};
Array.prototype.first = function () {
    return this[0];
};
Array.prototype.last = function () {
    return this[this.length - 1];
};
Array.prototype.average = function () {
    return this.sum() / this.length;
};
Array.prototype.range = function () {
    var self = this.sort();
    return {
        min: self[0],
        max: self[this.length-1]
    }
};
console.log(data.sum()) <-- 6

This makes working with arrays much easier if you need to do some mathematical processing on them. Are there any words of advice against using a pattern like this? I suppose I should probably make my own type that inherits from Array's prototype, but other than that, if these arrays will only have numbers in them is this an OK idea?

like image 239
wootscootinboogie Avatar asked Feb 21 '14 21:02

wootscootinboogie


People also ask

Can you extend array in JavaScript?

To extend an existing array in JavaScript, use the Array. concat() method.

Does array extend object?

For instance, Array extends Object . Normally, when one class extends another, both static and non-static methods are inherited. That was thoroughly explained in the article Static properties and methods.

How do I make a nested array?

Creating a Nested Array: This one is just equating the variable to the array. Second one is using the array method new Array() . And the last one is using the Array() which is similar to the new Array() . Note that all these methods yield the same result.

How do you add one array to another array?

Use the concat function, like so: var arrayA = [1, 2]; var arrayB = [3, 4]; var newArray = arrayA. concat(arrayB); The value of newArray will be [1, 2, 3, 4] ( arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).


1 Answers

Generally speaking you should avoid extending base objects because it may clash with other extensions of that object. Ideally extending Array and then modifying THAT is the safest way to do things as it is guaranteed to not clash with other developers who might try to do the same thing (even though they shouldn't).

Basically, avoid extending base objects when possible because it can get you into trouble for very little real benefit compared to extending the array object.

like image 56
moberemk Avatar answered Oct 14 '22 19:10

moberemk