Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding functions to javascript's Array class breaks for loops

I was looking for a way to add max/min functions to JavaScript's Array class, which seemed to be a solved problem: JavaScript: min & max Array values?. However, when I tried using that, I started getting errors from my code. It turns out that this approach doesn't work with loops.

for(i in myArray) { console.log(i) } 

prints out


1
2
3
max
min

Is there another approach I can use?

like image 485
Jeff Avatar asked Jun 13 '26 09:06

Jeff


1 Answers

The accepted solution solves your immediate problem, but extending core objects is generally a bad idea. What happens when you include a library later that uses for..in? Or when you forget months later and use the wrong approach in a different section of your code?

Another option is to wrap and extend. Create a new type that uses an instance of Array as its prototype:

function ArrayThing() {}

ArrayThing.prototype = new Array();

Now you've got an object that you can extend without affecting Array:

ArrayThing.prototype.max = function() {
    return Math.max.apply(null, [].slice.call(this, 0))
}

ArrayThing.prototype.min = function() {
    return Math.min.apply(null, [].slice.call(this, 0))
}

var list = new ArrayThing();

// standard array methods still work
list.push(5);
list.push(22);
list.push(0);
list.push(-14);
list.length // => 4

// as do your new custom methods
list.max() // => 22
list.min() // => -14

This won't work in every situation, but unless you're sure you really, really need an Array, this is a useful alternative.

like image 176
Wayne Avatar answered Jun 15 '26 00:06

Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!