I have challenged myself to combine the two exercises and add a form with a button:
On the page you enter the Start, End and Step of the Array.
Console will return the array and also the array in reverse.
It was harder than i thought but it finally worked out.
It is fun to play with, when you make large arrays you get interesting patterns in the console.
This could be a great exercise for all students.
How can i clear the form after the button is pushed?
I tried some stuff i found on the web but it did not work out.
Here is my code:
<html>
<head>
<title> Range Array </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<input id="inputStart" placeholder="Start" type="text">
<input id="inputEnd" placeholder="End" type="text">
<input id="inputStep" placeholder="Step" type="text">
<button id="rangeButton">Range</button>
<script>
//The sum of a range
function range(start, end, step) {
if (typeof step === 'undefined') {
step = 1;
}
var len = end - start + 1;
var outputArray = new Array(len);
for (let i = 0; i < len; i+= step) outputArray[i] = start + i;
//return outputArray;
var filtered = outputArray.filter(function (el) {
return el != null;
});
//delete all empty values (filter)
return filtered;
}
$("#rangeButton").click(function(){
var rangeStart = $("#inputStart").val();
var rangeEnd = $("#inputEnd").val();
var rangeStep = $("#inputStep").val();
console.log(range(parseInt(rangeStart), parseInt(rangeEnd), parseInt(rangeStep)));
console.log(reverseArray(range(parseInt(rangeStart), parseInt(rangeEnd), parseInt(rangeStep))));
});
/*Reverse Array
*/
function reverseArray(arr){
var rArray = [];
for(var i = arr.length - 1; i >= 0; i--){
rArray.push(arr[i]);
}
return rArray;
}
</script>
</body>
</html>