You need to return the array:
Array.prototype.power = function(value) {
for (var i = 0; i < this.length; i++) {
this[i] = Math.pow(this[i], value);
}
return this;
}
var powers = [1,2,3].power(2); // [1, 4, 9]
Going into more depth now, you may see the power
method listed as part of the Array when looking at the Array. This is one of the problems with prototyping the Array.
This doesn't mean that Array prototyping shouldn't be done. But understanding that, as an Array, it will still act like an Array so long as you used the Array methods in order to query/iterate it.
For example, taking the code example above, I can still get the correct length of the array:
powers.length; // 3
powers.toString() // 1,4,9
And if I iterate over it with index numbers, I can get an accurate reading:
for(var i = 0; i < powers.length; i++){
console.log(powers[i]);
}
// 1
// 4
// 9
Quite simply: [1, 4, 9]
are definitely the Array elements that are returned when using the power
method above.