Populating arrays with prompts using javascript

I'm currently working on a task that involves prompting the user to input random numbers until they enter "-1". Once this condition is met, I need to calculate the average of all the numbers entered excluding "-1". So far, here's what my code looks like:

var userInput;
while (userInput !== "-1") {
    userInput = prompt("Enter a number");
}
numbersList = [userInput];
console.log(numbersList);

Answer №1

Give this a shot

// Keep track of all numbers
const numberList = [];

let userInput;
for(;;){
    userInput = prompt("Type in a number");
    if(userInput === '-1') { break; }
    numberList.push(userInput);
}

// Calculate the average
let totalSum = 0;
let averageVal = 0;

numberList.forEach((val) => totalSum += val);

averageVal = totalSum / numberList.length

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

Tips for determining if the elements of an array are nearly identical

There is a collection of seven numbers in my array: array(159.60, 159.60, 159.60, 159.60, 159.60, 199.50, 199.50); array(395.68, 395.68, 395.68, 395.68, 395.68, 395.68, 395.68); array(531.18, 531.18, 531.18, 531.19, 531.18, 531.18, 531.18); I am facing t ...

Is it a good idea to relocate the document.ready function into its own JavaScript function?

Can the following code be placed inside a separate JavaScript function within a jQuery document.ready, allowing it to be called like any other JavaScript function? <script type="text/javascript"> $(document).ready(function() { $('div#infoi ...

Is it possible to open a new tab window using a radio button?

Looking for assistance with radio buttons. I want users to be redirected to a new window when they click the submit button beneath the radio buttons. If anyone has a solution, please help! I have tried using window.location.href and window.open but the c ...

I am looking to utilize React and Next.js to map my array from an object. The component is a function employing hooks

I am attempting to map an array within an object and encountering some challenges. The structure of the object is as follows: const data = {data: (6) [{…}, {…}, {…}, {…}, {…}, {…}], page: 2, per_page: 6, total: 12, total_pages: 2} I have been ...

Encountered an issue while trying to implement CORS using yarn

Currently experiencing the following issue: Error message: An unexpected error occurred "/home/vagrant/.cache/yarn/v1/npm-cors-2.8.4-2bd381f2eb201020105cd50ea59da63090694686/.yarn-metadata.json: Unexpected end of JSON input". Some important points to c ...

Using async await in a React component causes a syntax error

Struggling with setting up a basic react app using hapi.js on the server-side, I am diving into the world of webpack and babel as a newcomer. Here's a glimpse at my React component App.jsx: import React from 'react'; export default class A ...

The Canvas Clear function is malfunctioning; the items in the array are not being deleted

Even after being deleted from the array, the squares are still drawn. Shouldn't they disappear when removed from the Array? Does the array not update within the go function? Javascript: var canvas; var ctx; $(document).ready(function(){ $("#t ...

Utilizing Node.js and Express alongside EJS, iterating through objects and displaying them in a table

Today I embarked on my journey to learn Node.js and I am currently attempting to iterate through an object and display it in a table format. Within my router file: var obj = JSON.parse(`[{ "Name": "ArrowTower", "Class" ...

In the callback function within Array.prototype.map, make sure to access the newly created array

Array.prototype.map() creates a new array. How can I use this new array within the callback function passed to Array.prototype.map()? For instance: someArray.map(function(item, idx, arr) { return { theCreatedArray: xyz }; }); What should I assign to ...

Arranging data efficiently using Quicksort in C++

In my current school project, I have been tasked with sorting an array. After researching different algorithms, I decided to go with quicksort since it's a method that I'm not yet familiar with. Thankfully, I was able to grasp how it functions an ...

Moving the input box down to the lower portion of the screen

My goal is to create an interactive input box that glides smoothly to the bottom of the screen when clicked by the user. However, the current implementation causes the input box to move too far down, requiring the user to scroll down in order to see it. H ...

Updating a marker in real-time using API response

I'm trying to create a simple web application that allows users to enter a city name in an input box, which then triggers the updateMap function to geolocate and map the city with a marker. After mapping the city, another function called updateTemp is ...

Display a div using data from a Model in MVC

I am working with a model List that has fields ContainerId (div id) and Code (HTML code), which I am passing to a Razor View. Can you suggest the most effective way to display the code from the model in the containerId? My initial thought is to utilize j ...

Clicking on an iframe activates the loading of the displayed page

I'm attempting to create a functionality where clicking on an iframe will load the page it is displaying. I experimented with placing it within an tag, but that didn't produce the desired result. The effect I'm aiming for is similar to zoom ...

Replicating a tag and inputting the field content

Scenario: An issue arises with copying a label text and input field as one unit, instead of just the text. Solution Needed: Develop a method to copy both the text and the input field simultaneously by selecting the entire line. Challenge Encountered: Pre ...

Unable to reference a property or method in Vue.js and Vuetify due to an issue with the <v-btn-toggle> button causing an error

Just started using vuetify and exploring the <v-btn-toggle> component for the first time. I'm trying to implement a toggle feature to filter my user list based on employee, manager, or admin types... Check out a snippet of my code below: <v ...

Three.js: It seems that THREE.WebGLRenderer detected the image is not a power of two, originally sized at 1600x900. It was resized to 102

As I dive into learning three.js, one of my goals is to incorporate a 16x9 photo into my scene. Below is the snippet of code where I add an Array of images to my scene: const material = new MeshBasicMaterial({ map: loader.load(images[i]), trans ...

Using Vanilla Javascript to implement a dark mode toggle button

I've been struggling with getting a button to properly switch a website to dark mode. I already have a night mode that works based on the user's location and time, so I know the issue lies within my JavaScript... Initially, I tried adding ' ...

Sorting an object array by date is causing a problem

UPDATE: Finally cracked the code on this issue. I initially assumed that Date was interpreting the date ("29-04-2020") as DD-MM-YYYY, when it should actually be MM-DD-YYYY. For instance, here's an object array I'm working with: let t ...

What is the best way to modify a data parameter in Angular 2?

I am facing an issue while trying to change a data parameter in my component file: this.commandList.ListesCommandesATransmettre.forEach(data => { this.catalogs.forEach(catalog => { if (catalog.Libelle === data.Catalogue) { if ...