在 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 ]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP