Is there a way to execute a function for every element of an array using a for loop in Javascript?

I have been working on a script to calculate the sum of inputted numbers, including integers and "-" symbols. However, I am facing an issue where the code only calculates the sum for the first number in the array and then returns undefined. I understand that there may be a problem with my loop logic, but I'm not sure how to correct it.

Here is what I have tried:

var howM = prompt("How many cards?")

var arr = [];
for (var i = 0; i < howM; i++)
    arr.push(prompt("Enter a card:"));

console.log(arr)

var sumpre = [];

for (var i = 0; i <= howM; i++) {
    var sum = 0;
    var eXt = arr[i];
    eXt = eXt.replace(/-/g, "");
    for (i = 0; i < eXt.length; i++) {
        sum += parseInt(eXt.substr(i, 1));
    }
    sumpre.push(sum);
}
console.log(sumpre)

I also attempted this approach:

var howM = prompt("How many cards?")

var arr = [];
for (var i = 0; i < howM; i++)
    arr.push(prompt("Enter a card:"));

console.log(arr)

for (var i = 0; i < howM; i++) {
    var sum = 0;
    var eXt = arr[i]
    eXt = eXt.replace(/-/g, "");
    for (i = 0; i < eXt.length; i++) {
        sum += parseInt(eXt.substr(i, 1));
    }
}
console.log(sum);

If anyone has any suggestions on how to resolve this issue and ensure the calculation runs for each inputted number, please let me know. Your insights would be greatly appreciated!

Answer №1

To properly handle the nested for loop, it is essential to include a second counter in the code as shown below:

var numberOfCards = prompt("How many cards?")

var cardArray = [];
for(var i = 0; i < numberOfCards; i++)
  cardArray.push(prompt("Enter a card:"));

console.log(cardArray)

var sumArray = [];

for (var i = 0; i < numberOfCards; i++) {
  var totalSum = 0;
  var currentCard = cardArray[i];
  currentCard = currentCard.replace(/-/g, "");
  for (var j = 0; j < currentCard.length; j++) {
    totalSum += parseInt(currentCard.substr(j, 1)); 
  }
  sumArray.push(totalSum);
}
console.log(sumArray)

Answer №2

Having the var sum = 0; statement inside your for-loop will result in the sum variable being limited to only within the loop scope.

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

Troubleshooting the error "The 'listener' argument must be a function" in Node.js HTTP applications

I'm facing an issue resolving this error in my code. It works perfectly fine on my local environment, but once it reaches the 'http.get' call, it keeps throwing the error: "listener argument must be a function." Both Nodejs versions are iden ...

Protractor Throws Element Visibility Issue

When attempting to check a checkbox in the UI, I encounter an "ElementNotVisibleError: element not visible" error. Strangely, I am able to successfully capture and click the checkbox using the console in Chrome developer tools. Has anyone else experience ...

The chatbot text input feature is malfunctioning and failing to display the entered text in the chatbox

Hi there! I'm in the process of creating a chatbot using a basic input text box and button in HTML, with a php start function. Unfortunately, when I enter text into the textbox, nothing is showing up on the screen and the button doesn't seem to b ...

Removing elements from an array in mongoose using object ID list: A guide

Looking for assistance with a problem. The frontend provides me with a list of numbers that are IDs of objects to be removed. For example: { "user":"TEST", "conditionsToDelete":[1586513509594,1586513519698] } In my MongoDB documents, there is a prope ...

When looking at react/17.0.1/umd/react.development.js, it becomes evident that ReactDOM is not defined

I'm currently immersing myself in learning React with the help of React Quickly, written by Azat Mardan, which is based on React v15.5.4. The examples provided in the book typically include two essential files: react.js and react-dom.js, such as in th ...

Error: ReactJs unable to find location

I'm attempting to update the status of the current page when it loads... const navigation = \[ { name: "Dashboard", href: "/dashboard", current: false }, { name: "Team", href: "/dashboard/team", current: fa ...

"Troubles arising from the retrieval of a character pointer from a function

Upon entering the "recent" command, my code is called to retrieve previous commands: char* runRecent() { FILE *ffp; ffp = fopen("bash.txt","r"); char line[MAXLINE]; int fileItCount = 0; for (int i = 0 ; i < numLinesinFile ; i++) { ...

Is it feasible to evaluate a Typescript method parameter decorator at request time in a nodejs+nestjs environment rather than just at build time?

Looking to simplify my handling of mongodb calls with and without transactions in a single service method by writing a decorator. This would help eliminate the repetition of code and make things more efficient. Key points for usage: • Service class has ...

Surprise holdup encountered when getting back a string

Is there a specific reason why returning a string from a function is experiencing delays? Context: I developed a program that identifies anagrams of input letters by checking against a large text file. The program stores words in a vector and prints out a ...

Tips on Selecting a Typed Value

When clicking on 'no_results_text' and it's not available in the list, I want to show the searched value from the alert. I have included an onclick method for 'no_results_text', so that the typed value is displayed in the alert. h ...

Is it possible to sketch basic 2D shapes onto 3D models?

Is the technique called projective texture mapping? Are there any existing library methods that can be used to project basic 2D shapes, such as lines, onto a texture? I found an example in threejs that seems similar to what I'm looking for. I attempt ...

Tips for sending a callback function in Angular following an HTTP request

Currently, I am leveraging an angular controller to make an http post request to my express route. Subsequently, data is dispatched to my Gmail client via nodemailer. Although the $http request functions properly and emails can be received in my Gmail acco ...

Tips for incorporating a multiple tag search feature within my image collection using JavaScript?

I am facing a challenge with my image gallery search feature. Currently, users can search for images by typing in the title or tag of an image. However, I need to enhance this functionality to allow for multiple tags to be searched at once. For example, if ...

infinite loop issue with beforeRouteEnter

I'm experiencing an issue with Vue Router. The scenario is to load / initially, retrieve data from there, and then navigate to the /chat/:chatId route to display the interface using the :chatId parameter obtained from an API. The routes configured a ...

Multiply elements in an array by using a recursive for loop algorithm

Currently, I am in the process of developing a program that involves multiplying elements in a 2D array with elements in subsequent rows. To accomplish this, I have implemented a recursive method that initially traverses each row of the 2D array, identif ...

Deleting files with a dedicated function (Dropzone.js)

I need to implement functionality that removes the uploaded file when a 'cancel' button is clicked. Here's how my HTML code looks: <div reqdropzone="reqDropzoneConfig"> <form id="requisitionupload" class="dropzone dz-clickable" ac ...

Utilize a JSON document in conjunction with running JavaScript code

I have a PHP file that returns JSON data. However, I am looking to include some javascript (specifically Google Analytics code) in the file. Below is the code snippet: <?php header('Content-Type: application/json'); //GOOGLE ANALYTICS ...

Unable to implement the checkCollision function within the Snake game using JavaScript

My latest project involves creating a Snake game using canvas in JavaScript. I've managed to set up most of the game, but I'm having trouble with the collision check. Whenever the snake hits itself or the wall, the game crashes because I can&apos ...

How come my jQuery ajax request is successful but the $_POST array remains empty?

Here is my first query on this forum, please be patient with me: The code snippet for my ajax request is: <script> $.ajax({ type:"POST", url:"http://localhost/folder/something.php", data: { BuildingName:'Jacaranda'}, success: function(da ...

Iterating through an array of structures in C

Let's discuss struct declaration with an example: struct mystruct { char a[10]; double b; } struct mystruct array[20] = { {'test1',1.0}, {'test2',2.0} <---- Initially, only 2 items are declared for future addition ...