[英]How to extend the javascript Array Class?
I am trying to extend the Array class to add a Sum method to it.我正在尝试扩展数组 class 以向其添加 Sum 方法。 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预期 output = 10
reduce
). reduce
)。 this
to refer to the array. 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());
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);
Inside of the sum
method, you refer to the array via this
. 在
sum
方法内部,您可以通过this
引用数组。
I'm sorry, but I had to downvote the question as it seems to me more like asking for the solution of a homework after doing half the research on how to code in javascript.对不起,但我不得不否决这个问题,因为在我看来,在对如何在 javascript 中进行编码进行了一半研究之后,我更像是在寻求家庭作业的解决方案。
class
in javascript needs to be lowercase.class
中的 class 需要小写。i
to total
, but what was the initial value of total
?i
添加到total
中,但是total
的初始值是多少? Declare the total
variable before the for loop as let total = 0
total
变量为let total = 0
i
also needs to be declared as for (let i in values) {
i
也需要声明为for (let i in values) {
return total
after your for loop so that the function would return something.return total
,这样 function 就会返回一些东西。testArray = [1,2,3,4]
, as that line is the same as testArray = new Array(1, 2, 3, 4);
testArray = [1,2,3,4]
,因为该行与testArray = new Array(1, 2, 3, 4);
. var testArray = new tipArray(1, 2, 3, 4)
or testArray.push(1, 2, 3, 4)
.var testArray = new tipArray(1, 2, 3, 4)
或testArray.push(1, 2, 3, 4)
。 In essence the solution should be what Geuis wrote.本质上,解决方案应该是 Geuis 所写的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.