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 新房祝福语简短10字
14 长辈新年祝福语大全简短
15 新年给大家简短祝福语
16 生日祝福语简短独特姑姑
17 芭比的婚礼祝福语简短
18 邀请新人祝福语简短英文