Create a JavaScript array using the window.prompt() method

Trying to create a JavaScript array with user input for the number of elements and element values using window.prompt().

This is my current code :

var n = window.prompt("Enter the number of elements", "")
var nums = new Array(n)
for (i = 0; i < n; i++) {
  nums[i] = window.prompt("Enter number: ", "")
}
for (i = 0; i < n; i++) {
  if ((i + 1) % 2 != 0) {
    if (nums[i] % 2 == 0)
      document.write("Even numbers at odd positions are: ", nums[i], "<br/>")
  }
}
document.write("The numbers are :")
for (i = 0; i < n; i++) {
  document.write(nums[i] + "<br/>")
}

No output is displayed on the webpage.

Answer №1

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/>")
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Prevent users from taking screenshots by disabling the print screen key

Can someone help me figure out how to prevent users from taking a screenshot of my website by disabling the print screen key? Here's the code I've tried so far: <SCRIPT type="text/javascript"> focusInput = function() { document.focus() ...

A guide on retrieving real-time data from PHP using Ajax

Being new to Ajax, I am struggling to grasp how to retrieve changing variable values from php. Below is the code snippet that I have been working on: <?php $pfstatetext = get_mypfstate(); $cpuusage= cpu_usage(); ?> <div id="show"> <c ...

Float: A threshold reached when adding 1 no longer has any effect

In the realm of programming, float serves as an estimation of a numeric value. For example, 12345678901234567890 === 12345678901234567891 evaluates to true However, 1234567890 === 1234567891 yields false Where does the equation num === num+1 reach a br ...

Obtain location data based on the adaptability of the design

As part of my plugin development, I want to track and save user mouse movements to create a heatmap representation. One challenge I'm facing is how to dynamically adjust the coordinates for different screen sizes as elements shift based on device widt ...

Creating an array of structs by passing a struct as a parameter

I am attempting to build an array of structs using a function that retrieves data from firestore and then assigns the fetched structs to an array. Here is my code snippet: func fetchUsers() { var user1: User var user2: User var user3: User ...

Array remains allocated after leaving scope

In my program, I am using a char array to read data from a pipe. This array is utilized within an infinite while loop. int main() { mkfifo("process1_write", 0666); mkfifo("process1_read", 0666); int fd1,fd2; fd1 ...

The input type '{}' does not match the expected type 'Readonly<IIdeasContainerProps>'. The property '...' is not found in the type '{}'

Having recently started using TypeScript, I'm encountering some issues when attempting to execute this code snippet. Error The error message reads as follows: Failed to compile 13,8): Type '{}' is not assignable to type 'Readonly &l ...

When utilizing Nettuts' CSS navigation resource, the bottom shadow will disappear if the parent element contains child elements

I'm currently working on customizing a solution I stumbled upon on Nettuts to fit my specific requirements. Everything seems to be functioning well, except for a peculiar issue I'm encountering while hovering over a top-level navigation element t ...

Understanding special characters within a URL

Here is a URL example: postgres://someuser:pas#%w#@rd-some-db.cgosdsd8op.us-east-1.rds.amazonaws.com:5432 This URL is being parsed using the following code snippet: const url = require('url'); const { hostname: host, port, auth, path } = url.par ...

Node.js tutorial: Fetching all pages of playlists from Spotify API

Currently, I am attempting to retrieve all of a user's playlists from the spotify API and display them in a selection list. The challenge lies in only being able to access 20 playlists at a time, which prompted me to create a while loop utilizing the ...

Troubleshooting the search functionality in jQuery DataTables: JavaScript issues

In my table, I have included a button for action, but because of that the search functionality is not working on the table. Check out the demo:https://jsfiddle.net/pkxmnh2a/33/ $(document).ready(function() { var table = $('#examples').DataT ...

What is the best approach for choosing an object's properties by delving into its nested properties with Lodash?

My dilemma involves selecting the properties of an object based on certain values within the nested properties. I have been attempting to achieve this using Lodash's pick() method, with the code looking something like this: const object = { a ...

AngularJS does not allow access to the variable value outside of the resource service's scope,

I have developed an AngularJS factory service to handle REST calls. The service is functioning correctly, but I am facing a challenge where I need to set values into $scope.variable and access them outside of the resource service. However, when attempting ...

Steps to initiate an iframe event using Jquery

Is there a way to trigger an event within an iframe from the parent document? Here's a hypothetical scenario of what I am attempting to achieve: <iframe id="i"> <div id="test"></div> <script> $(document).ready(function( ...

How can I send back multiple error messages from a pug template in a node.js application with Express?

I am currently working on validating inputs from a form on a Node.js web server using Pug.js and Express.js. The issue I am facing is that when there are multiple problems with the user's input, only the first error is displayed to the user. How can I ...

What is the best way to sort strings in alphabetical order using Ruby?

Wondering how I can alphabetically sort a series of strings from an array using a loop in Ruby. Any tips on the most simple approach to accomplish this task? ...

Error in chaincode argument: incorrect character ':' following array element

When attempting to pass a JSON value as an input (value) to a specific key in hyperledger invoke chaincode, the following error message is displayed: Error: chaincode argument error: invalid character ':' after array element Usage: peer chainc ...

Tips for achieving printing with the "Fit sheet on one page" option in JavaScript

Is there a way to print a large table of data with 200 or 300 rows all on one page, similar to the Online MS Excel print option 'Fit Sheet on One Page'? I attempted the code below: var tble = document.createElement("table"); tble.id = "tble"; d ...

Using Javascript to add an onclick event to an HTML form button

I am facing an issue where I need to change the text inputs in a form to black color after clicking the "Reset button" using Javascript. Although I thought about utilizing onReset in the HTML to tackle this problem, it's mandated that I resolve this ...

Obtaining binary data directly from a combination of buffers

When working with the nodeJS Buffer().toString('utf8'), I encountered the following: Content-Type: audio/x-ms-wma Content-Disposition: form-data; name=recordedAudio \r\n\r\n0&uf\u0011\u0000 My goal is to strip ...