在 JavaScript 陣列中求解範圍內的總和


我們需要編寫一個數組函式(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 ]

更新日期: 2020-11-21

281 次瀏覽

職業起步

完成課程以獲得認證

開始
廣告