在 JavaScript 数组中求解范围内的总和
我们需要编写一个数组函数(Array.prototype 对象上的函数)。此函数应接收一个起始索引和一个结束索引,并对数组中从起始索引到结束索引(包括起始索引和结束索引)的所有元素求和
示例
const arr = [1, 2, 3, 4, 5, 6, 7];
const sumRange = function(start = 0, end = 1){
const res = [];
if(start > end){
return res;
};
for(let i = start; i <= end; i++){
res.push(this[i]);
};
return res;
};
Array.prototype.sumRange = sumRange;
console.log(arr.sumRange(0, 4));输出
而在控制台中的输出将是 −
[ 1, 2, 3, 4, 5 ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP