I am trying to extend the Array class to add a Sum method to it. This is my code below, what am I doing wrong?
Class tipArray extends Array{
sum(values) {
for(i in values) {
total +=i;
}
}
}
var testArray = new tipArray();
testArray = [1,2,3,4];
console.log(testArray.sum());
Expected output = 10
Advertisement
Answer
- Start by imagining how you would sum an array (maybe something with
reduce). - Turn that into a function.
- Add that as a method on your class. You can use
thisto refer to the array. - (optional) ask yourself if you really need a subclass instead of a function that accepts an array.
class tipArray extends Array{
sum() {
// Consider making sure the array contains items where sum makes sense here.
return this.reduce((sum, current) => sum + current)
}
}
var testArray = new tipArray(1,2,3,4);
console.log(testArray.sum());
// add another element and take another sum
testArray.push(10)
console.log(testArray.sum());