JavaScript在数组中查找范围的总和
我们需要编写一个Array函数(位于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 ]
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短