我正在尝试扩展Array类以向其添加Sum方法。这是下面的代码,我在做什么错?
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());
预期输出= 10
答案 0 :(得分:3)
reduce
来求和)。 this
来引用数组。
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());
答案 1 :(得分:0)
class tipArray extends Array {
sum() {
let val = 0;
for (let i = 0; i < this.length; i++) {
val += this[i];
}
return val;
}
}
var testArray = new tipArray(1, 2, 3, 4);
console.log(testArray.sum());
console.log(testArray.length);
在sum
方法内部,您通过this
引用数组。