Challenge with printing the elements in the array

As a beginner in programming and Stack Overflow, please excuse my lack of understanding. I am struggling to print out the last three arrays in my code - it only prints out the last element in each array. However, when I use console.log, all the elements are displayed. I hope this explanation makes sense. Any assistance on resolving this issue would be greatly appreciated. Thank you.

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="">
</head>

<body>
  <h1>Score Sheet</h1>
  <script type="text/javascript">
  var candidateName = [];
  var candidates = 0;
  var moreCandidates = "y";

  while (moreCandidates == "y"){
    candidateName.push(prompt("Enter candidate name"));
    var noOfSubjects = prompt("How many subjects are you offering?");

    for(i = 1; i <= noOfSubjects; i++){
      var subName = [];
      var scores = [];
      var unit = [];
      subName.push(prompt("What is the subject name?"));
      console.log(subName);
      scores.push(prompt("Enter your subject score"));
      console.log(scores);
      unit.push(prompt("Enter your subject unit"));
      console.log(unit);
    }

    moreCandidates = prompt("Do you want to add more candidates? y/n");
    candidates++
 }

 document.write("Number of candidates is" + " " + candidates);
 document.write("<br/>");
 document.write(candidateName);
 document.write("<br/>");
 document.write(noOfSubjects);
 document.write("<br/>");
 document.write(subName);
 document.write("<br/>");
 // document.write(scores);
 // document.write("<br/>");
 // document.write(unit);

</script>

Answer №1

The issue lies in resetting the arrays within each loop iteration, resulting in them only containing one value at a time. It would be more effective to declare them outside of the loop.

Remember to use var for i, otherwise it will be globally defined. Additionally, consider implementing a proper interface instead of relying on prompt() for user input for a better user experience.

var subName = [];
var scores = [];
var unit = [];

for(var i = 1; i <= noOfSubjects; i++){
    subName.push(prompt("What is the subject name?")); 
    console.log(subName);
    scores.push(prompt("Enter your subject score"));
    console.log(scores);
    unit.push(prompt("Enter your subject unit"));
    console.log(unit);
}

If you prefer using document write, you can utilize join() like this:

document.write(scores.join(", "))

This will display the array values as a string on the page.

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

Ignoring a basic error or rule check within a loop_IGNORE

I want to generate a series of unique numbers with each iteration, ensuring that no number is repeated. Despite adding a check to prevent duplicate numbers, the code seems to be ignoring it and occasionally adds the same number more than once. $data = ar ...

Error in Typescript with a Bluebird library: The 'this' context is not compatible with the method's 'this' context

I have a collection of methods (some synchronous and some asynchronous) that I wish to process sequentially using bluebird.each. Here's a simplified example: import bluebird from 'bluebird'; const delay = (ms: number) => new Promise((res ...

Why does printf not accept just the address of 'argv' as input, given that it can print a string using an address?

int main(int argc, char **argv){ printf("argv: %s\n",argv); // The output is unpredictable printf("*argv: %s\n",*argv); // Works fine and prints ".a.out" } Testing with: ./a.out nop Here's my dilemma: ...

Having trouble loading HDRI image as environment using Three.js

I recently started using Three.js and am currently tackling a project that involves utilizing an HDRI file for environmental mapping for lighting and reflection purposes. I've been experimenting with loading HDRI files using the HDRCubeTextureLoader a ...

Can you provide tips on how to center the title on the page?

Currently, I am working on codepen.io and have been tasked with creating a paragraph that includes a title. However, my dilemma lies in the fact that I need this title to be center-aligned without directly altering the "x" value. Unfortunately, CSS is not ...

Steps for transforming a PHP array into an associative array by utilizing the index as keys

I have an array called $foo that contains strings and nested arrays: $foo = ["hello", "hi", [5, 10]]; I am looking to transform this array into an associative array where the keys correspond to the original index: $foo = [ "0" => "hello", "1" = ...

What is the most effective method for embedding a Kotlin program into a website?

I have created a combat simulation tool in Kotlin for an online gaming community. Users can input the combat levels of two players, choose the number of duels to simulate, and then initiate the simulation which will provide win percentages and other stats. ...

javascript: verify the presence of uppercase and lowercase letters

Can the validation of at least 2 lowercase and 2 uppercase letters be implemented when checking the case? Below is the condition I am currently using. function HasMixedCase(passwd){ if(passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) return true ...

Can someone help me troubleshoot this issue with my code so that my website can open in a blank page using about:blank?

I'm currently facing an issue while trying to make one of the pages on my website open with an about:blank URL upon loading. Despite embedding the code in my index.html file, it doesn't seem to be functioning properly. Here's the code I&apos ...

Show or hide the sibling element of the current element without using a specific identifier in jQuery

I am looking to make div.edit-button toggle its corresponding sibling div.additionalFieldForm. There are multiple instances of both on the page, so I want to target only the pair that are related within the same group. If a div.edit-button is clicked, the ...

Testing a service resolution in a controller through unit testing

As I attempt to create a test for my home module, I keep encountering an error that reads "unknown provider: service." Interestingly, when I modify resolveSomething in my home module to output a string, the app functions as expected, indicating that the re ...

Steps for incorporating events on Jquery UI button

I have a question about utilizing Jquery UI for the first time. After successfully adding a button using Jquery UI, I am now interested in adding events for when a radio switch is turned on and off. When the radiobox is switched on, I want an alert window ...

Activate single elements one at a time

If you want to understand the question better, take a look at my code on jsfiddle. Each Div contains only one link. When you click on the link, it sets the Div to active and shows a hidden Div within it. Clicking the link again toggles the active style an ...

Manipulating object properties within an array through iteration

Here is the array I am working with: var data = [ {"firstname":"A","middlename":"B","lastname":"C"}, {"firstname":"L","middlename":"M","lastname":"N"}, {"firstname":"X","middlename":"Y","lastname":"Z"} ]; I need to update the values for all keys - firstn ...

Display temporary image if image is not located

I attempted to utilize the onerror attribute to display a placeholder image when the desired image is not found in the folder. The image path is dynamically generated from the backend. The code snippet below shows how I implemented this: <img class=&quo ...

Using jQuery and Perl to create a dynamic progress bar that is based on the current state of a "pipeline file" and utilizes AJAX

I'm looking to create a small pipeline that enables users to select a file and run multiple scripts using it as an input. Some of these scripts may take several minutes to complete (time depends on the file's size), so I want to display a progres ...

Guide on transferring data from a 2D Variable Length Array to a resizable array (referred to as a matrix) in the C programming language

Currently, my goal is to develop a Linear Algebra library using C from scratch. My initial approach involved creating a matrix with a struct. The matrix's dimension and size are allocated dynamically. I aim to create a function that will allow me to c ...

The function FormatCurrency is non-existent

I need assistance with converting a textbox value into a currency using the jquery.formatCurrency-1.4.0.js plugin. My JavaScript function is set up like this: $(document).ready(function() { $('.currency').blur(function() { $(&apo ...

Transferring binary data from C# to Node.js for deserialization

I am facing a challenge where I have a byte array created in C# from an object type, which is then sent over the socket protocol to a Node.js app. However, I am unable to deserialize the data into a readable object. Can anyone suggest a way to decode this ...

What method can be used to incorporate Google Places API into a .js file without using a <script> element?

As I delve into the Google Places API documentation, I noticed that they require the API be loaded in this format: <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script> Is ...