Encounter a JavaScript syntax error when attempting to push undefined data

I am in the process of developing a program that prompts the user to enter values to store in an array. The program will continue to ask for more values until the user decides to stop entering numbers into the array. Once all the values are inputted, I need to display the array without any zeros (as users are permitted to include zeros) and calculate the sum of the array. One issue I have encountered with my current implementation is that arr.push(x) seems to be attempting to add an undefined value in the function arrin. I believe there may be a better approach to solving this problem, so I am open to suggestions for improvement.

var x = parseInt(prompt("Enter a number, or type NaN to exit", "0"), 10);

var y = arrin(x); 

var arr = [];

var s;

function arrin(x) {

if(x != NaN){
    arr.push(x)
    x = parseInt(prompt("Enter a number, or type NaN to exit", "0"), 10); 
    y = arrin(x);
}else{
    document.write("<p>"+arr.toString()+"</p>");
    s = sum(arr);
    doucment.write("<p> The sum of all elements in the array is "+s+"</p>");
}

}

Answer №1

The condition x != NaN is not effective.

Using !isNaN(x) will help in verifying if the variable is a number.

To check if the text is exactly "NaN", use the condition x != "NaN".

Either of the last two conditions mentioned above will produce the desired result.

A JavaScript code snippet demonstrating array manipulation:
var arr = [];
var y = arrin(0);
var s;

function arrin(x) {

  if (!isNaN(x)) {
    if (x !== 0) arr.push(x)
    x = parseInt(prompt("Enter a number, to exit enter NaN", "0"), 10);
    y = arrin(x);
  } else {
    document.write("<p>" + arr.toString() + "</p>");
    s = sum();
    document.write("<p> The sum of all elements in the array is " + s + "</p>");
  }
}

function sum() {
  var t = 0;
  for (var i = arr.length; i--;) t += parseInt(arr[i]);
  return t;
}

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

Issues with jQuery autocomplete when using special characters (Norwegian)

On my website in Norway, I am facing an issue with jQuery's autocomplete function. When users type in the Norwegian characters æ, ø, and å, the autocomplete feature suggests words with these characters within them but not ones that start with these ...

Using Arrays in Combination with React

After creating a list, I found myself in unfamiliar territory: let myList = [ { id: 'budget', label: 'Budget', widget: <Budget />, checked: true }, { id: 'lastEmployees', l ...

The reason behind the creation of .pnp.loader.mjs and .pnp.cjs files by yarn

While working on my React project with Vite, I noticed that when using yarn to start the "live server," two new files are created: .pnp.loader.mjs and .pnp.cjs. Can anyone explain what these files are for? I've never come across them before as I usual ...

Could use some help with configuring express routes with parameters

Greetings! I am new to working with Express and I am currently in the process of creating a portfolio website. In my project, I have a Pug file named project.pug which includes HTML content that should dynamically render based on the ID of each project sto ...

I am experiencing an issue where jQuery is not functioning properly within my Groovy Server Page

In my Groovy Server Page, I am struggling with a jQuery function that is not running as expected. When my controller's function renders an error message, it appears on the "next" web page instead of on the same page using Ajax. I double-checked that j ...

Is there a way to dynamically modify a website's default viewport settings in a mobile browser?

When viewing a website in Landscape mode, everything looks good. However, switching to Portrait mode displays the message "Screen size not supported." I decided to test this on my desktop browser and discovered that adjusting the initial-scale:1 to initial ...

What causes the conflict between Nodejs usb module and Electron?

Apologies for the lengthy post, but I've been tirelessly searching for a solution online without any luck. My goal is to create a basic Electron application that can display an HTML page (which is working fine) and control a printer through the USB mo ...

$(document).on("click" .. selecting first this and then that specific element

I have a single checkbox and two radio buttons to choose from. If the user selects "wedding" from the checkbox and "boys" from the first radio button, I want to display another set of radio options under the class ".coaches". Although I've followed ...

Unexpected background image slideshow appearance

I am encountering an issue with my slideshow where the last image briefly appears before the first image loads in a continuous loop. The offset of the initial image causes it to start at the middle of the window, and in Google Chrome and Safari, subsequent ...

Adjusting the transparency of an image within a frameset embedded in an iframe

I added a transparent box using CSS to my main HTML. Within the box, I included an iframe that is linked to another frameset consisting of four frames. <div class="box"> <h1>World Map</h1> <iframe style="border:2px solid black;" src=" ...

Include an array in the key attribute of the web.config file

Is it possible to include an array as a value in a key? For example: <add key="email" value="emails["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee8b838f8782dfae8b838f8782c08d8183">[email protected]</a>, &l ...

Does Next.js pre-render every page, or does it only pre-render the initial page?

As I dive into the world of nextjs, I'm coming across conflicting information. Some sources claim that nextjs only prerenders the first page, while others suggest that all pages are prerendered by default. This contradiction has left me confused about ...

Encountering an issue with Meteor and node-celery: "Unable to access property 'slice' of null"

Check out the Github repository for reproducing this issue Run localhost:3000 to replicate the problem. In my setup with Meteor 1.4.4.1, I am utilizing the node-celery npm packages on the server side. Upon Meteor initialization, the client automatically i ...

Is passing a JavaScript variable to a function in Java feasible?

I am currently developing a JSP web page which includes an input text field where users can choose a date. I need to retrieve this selected date value and update it in my database by invoking a Java method that I have created. The HTML for the input field ...

Storing a JSON array in a Java ArrayList: Best practices

I have limited knowledge about Json, but I am currently working on an Android project. I am familiar with using ArrayLists in Java. In my Android Project, I have a Json file stored in the Asset folder. Can someone please guide me on how to parse this file ...

Sequentially traverse the tree in reverse preorder fashion

My goal is to locate the element that is positioned directly above another element in the layout. This could mean the element is nested within several levels of the DOM structure, or it may involve moving up a few levels in the hierarchy. For instance: di ...

Effective approach for managing a series of lengthy API requests

I am developing a user interface for uploading a list of users including their email and name into my database. After the upload process is complete, each user will also receive an email notification. The backend API responsible for this task is created u ...

Loading JQuery dynamically from an externally linked JavaScript file

Our clients can easily add a short script to their website to load our application. This script asynchronously loads the JavaScript that triggers the application on the client's page, typically as a pop-up. The launch code for the application requires ...

Utilizing Chart.js to visualize live data from a dynamic MySQL dataset

Struggling to create a dynamic dataset for my Chart.js project, specifically with the data obtained from getpromorevenuechart.php. Here's an example of the dataset: [{"mmyy":"2019-12","promocode":"promo1","amount":"2776"},{"mmyy":"2020-01","promocode ...

Converting custom format into an array

I am facing a challenge in converting a specially formatted .txt file into an array format. Let me share with you a snippet of the initial lines from the file: [LINETYPE]S [STARTTIME]00:00:00 [LINETYPE]M [TITLE]There For You [PERFORMER]Martin Garrix & ...