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 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短