- Write a range that takes two arguments “start” and “end”, and returns an array containing all the numbers from “start” up to (and including) “end”.
function range(start, end) {
var sum =0;
for (var i = start; i <= end; i ++)
sum += i;
document.write(sum);
}
range (1,10);
console.log(sum(range(1, 10)));
- Write the sum of a function that takes an array of numbers and returns the sum of those numbers.
function range(start, end){
let arrayRange = [];
for (i = start; i<=end; i++) {arrayRange.push(i);
}
return arrayRange;
}
console.log (sum(range(1, 10))):
- Modify the “range” functions to take an optional third argument that indicates the “step” value used when building the array.
function range(start,end,step){
let array=[];
for (i=0; i<=(end-start)/step; i++){
array.push(start+i*step);
}
return array;
}
console.log (range(5, 2, -1));
- Write a function that takes an array as an argument and produces a new array that has the same elements in the inverse order.
function reverseArray(array) {
let newArray = [];
for(i = array.length - 1; i >= 0; i–) {
newArray.push(array[i]);
}
return newArray;
}
console.log(reverseArray([“A”, “B”, “C”]));
- Write a function that also modifies the array given as an argument by reversing its elements.
function reverseArrayInPlace(array){
for (let i = 0; i < Math.floor(array.length / 2); i++) {
let old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
console.log(reverseArrayInPlace([“1”,“2”,“3”,“4”,“5”]));