Defining the essentials.
The crucial starting point in your code is to establish an array like so:
var numbers = [];
This array will serve as a container for all the elements received via input. To begin, you must determine the total number of values needed by prompting the user:
var times = window.prompt("Specify the quantity of numbers: ");
Here, the variable times
stores the number of inputs required from the user and these will be stored in the numbers
array.
Prompting the user for multiple numbers.
To collect the user's input for the specified number of times, a simple for loop can be utilized to push each new number into the array:
for (let i = 0; i < times; i++) {
numbers.push(window.prompt(`Number ${i+1}: `))
}
Upon execution, this loop prompts the user for each number with a message indicating the position of the input.
Validation for even and odd numbers.
To implement a feature that identifies even numbers at odd indices, the following operation can be performed:
numbers.forEach((n,i)=>{
if(n%2===0 && i%2!=0){
document.write(`Even number ${n} at odd index ${i} <br/>`);
}
});
This function iterates through the user-provided numbers, checking if an even number is situated at an odd index
, and displays only when this condition holds true.
Displaying the collected numbers.
To showcase all the entered numbers, a further simple step is to iterate through the array and output each number:
numbers.forEach((n)=>{
document.write(n + "<br/>")
});
Observe the script in action:
var times = window.prompt("Insert number of numbers"), numbers = [];
for (let i = 0; i < times; i++) {
numbers.push(window.prompt(`Number ${i+1}: `))
}
numbers.forEach((n,i)=>{
if(n%2===0 && i%2!=0){
document.write(`Even number ${n} at odd index ${i} <br/>`);
}
});
document.write("The numbers are: <br/>")
numbers.forEach((n)=>{
document.write(n + "<br/>")
});