利用prototype,给数组添加一下方法sum(),返回个数组中所有的数据元素的和
时间: 2024-05-16 20:12:14 浏览: 4
好的,问题很简单,可以直接回答。以下是代码实现:
```javascript
Array.prototype.sum = function() {
return this.reduce((acc, cur) => acc + cur, 0);
};
//测试
const arr = [1, 2, 3, 4, 5];
console.log(arr.sum()); //15
```
相关问题
js中 给Array.prototype添加sum方法,按回所有的数组元素的和。 添加unique()方法,完成数组的去重。
给Array.prototype添加sum方法:
```javascript
Array.prototype.sum = function() {
return this.reduce((acc, cur) => acc + cur, 0);
}
```
给Array.prototype添加unique方法:
```javascript
Array.prototype.unique = function() {
return Array.from(new Set(this));
}
```
或者
```javascript
Array.prototype.unique = function() {
let arr = [];
for (let i = 0; i < this.length; i++) {
if (!arr.includes(this[i])) {
arr.push(this[i]);
}
}
return arr;
}
```
给数组的原型对象添加方法,getMax,getMin,getAvg,求数组元素的最大值,最小值,平均值
Array.prototype.getMax = function() {
return Math.max.apply(null, this);
}
Array.prototype.getMin = function() {
return Math.min.apply(null, this);
}
Array.prototype.getAvg = function() {
var sum = this.reduce(function(acc, val) {
return acc + val;
}, 0);
return sum / this.length;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)