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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短