查找数组中某个范围的总和 JavaScript
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个数组函数(存在于 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 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

