Scope of an array being passed

I have a challenge of passing an array from one external .js file to another. The individual files are functional on their own, however, the issue arises when trying to pass the array from pickClass.js to displayStudent.js and displaying the names along with the "remaining" value in the html file. It seems like the problem lies in how the arrays are declared, but I am struggling to make it work correctly.

The initial file declares the array choice (masterStudentList.js):

var class1 = ['Brown, Abe','Drifter, Charlie','Freed, Eve'];
var class2 = ['Vole, Ug','Xylo, William','Zyzzyx, Yakob']; 

The second file selects which array to use based on radio buttons (pickClass.js):

var classPicked = array(1); 

 function randomize(){
   return (Math.round(Math.random())-0.5); } 

 function radioResult(){
 var chooseClass = document.getElementsByName("chooseClass");

 for (i = 0; i < chooseClass.length; i++){currentButton = chooseClass[i];
    if (currentButton.checked){
      var selectedButton = currentButton.value;
    } // end if
  } // end for

var output = document.getElementById("output");
var response = "You chose ";
 response += selectedButton + "\n";
 output.innerHTML = response;

 chosenClass = new Array();
if (selectedButton == "class1")
{chosenClass = class1;}
else
{chosenClass = class2;}

var text = "";
var nametext = "";
var i;
    for (i = 0; i < chosenClass.length; i++) {
    text += chosenClass[i]+ ' / ';
}


var showText = "";  
 l = chosenClass.length;
 classPicked = Array(l);   
 for (var i = 0; i < l; ++i) {
 classPicked[i] = chosenClass[i].split(', ').reverse().join(' ');
 showText += classPicked[i]+ '<br>';

}
 //return = classPicked;
document.getElementById("classList").innerHTML = classPicked;  

 } // end function

Everything is functioning as intended at this stage.

Next, I aim to transfer "classPicked" to another .js file (displayStudent.js) that will randomize the student list, present the students for a few seconds, and then conclude with showcasing one student name.

basket = classPicked;  //Here's where the array must be passed

function randOrd(){
return (Math.round(Math.random())-0.5); } 

 function showBasket(){
  mixedBasket = basket.sort( randOrd ); //randomize the array
  var i = 0;  // the index of the current item to show
  document.getElementById("remaining").innerHTML = basket.length; 

 fruitDisplay = setInterval(function() {            
   document.getElementById('showStud')
    .innerHTML = mixedBasket[i++];    // get the item and increment
 if (i == mixedBasket.length) i = 0;   // reset to first element if you've reached the end
  }, 100);  //speed to display items

 var endFruitDisplay = setTimeout(function() 
 { clearInterval(fruitDisplay); 

 var index = mixedBasket.indexOf(document.getElementById('showStud').innerHTML); 

 mixedBasket.splice(index,1); 

  }, 3500); //stop display after x milliseconds
 }

Below is the HTML layout (master.html) - still a work in progress:

<html>
   <head>
 <script src="masterStudentList.js" type="text/javascript"></script>
 <script src="pickClass.js" type="text/javascript"></script>
 <script src="displayStudent.js" type="text/javascript"></script>
 </head>
 <body>
  <h2>Choose Class</h2>
 <form action = "">
 <fieldset>
 <input type = "radio"
 name = "chooseClass"
 id = "radSpoon"
 value = "class1"
 checked = "checked" />
 <label for = "radSpoon">Class 1</label>
 <input type = "radio"
 name = "chooseClass"
 id = "radFlower"
 value = "class2" />
 <label for = "radFlower">Class 2</label>

 <button type = "button"
  onclick = "radioResult()"> Choose Class
 </button>
 <div id = "output">
 </fieldset>
 </form>

 </div>

<center>
<h1> <span id="chooseStud"></span><p></h1> 

 <script> var fruitSound = new Audio(); 
      fruitSound.src = "boardfill.mp3"; 

    function showFruitwithSound()
    { 
    fruitSound.play(); // Play button sound now 
    showBasket()
    } 
</script>

Remaining: <span id = "remaining" ></span>

<p>
<button onclick="showFruitwithSound()">Choose Student</button>

</center>  

pickedClassList = <p id = classList> </p>

</body>
</html>

Answer №1

Avoid using global variables in this way (I recommend further reading on this topic) and it seems like I may not fully grasp your intentions... However, the solution to your problem should involve moving the basket = classPicked; line into your showBasket method :

basket = classPicked;  //This is where the array should be passed

function randOrd(){
  return (Math.round(Math.random())-0.5);
}

function showBasket(){
  // whatever
}

This should be rewritten as :

function randOrd(){
  return (Math.round(Math.random())-0.5);
}

function showBasket(){
  basket = classPicked;  //This is where the array should be passed
  // whatever
}

By doing this, each time showBasket is called, it will utilize the latest value of classPicked. Otherwise, basket will always point back to the initial value of classPicked.

Why? Because when you assign a new Array to the basket variable (classPicked = Array(l);) instead of altering its content directly by :

  • emptying it :
    while (classPicked.length > 0) { classPicked.pop(); }
  • and then adding new data : classPicked.concat(chosenClass)

Answer №2

Transferring data to files is not possible; however, a workaround would be to utilize a function from displayStudent.js, passing in the variable classPicked and having it assign that value to basket.

Answer №3

Upon reviewing your second block of code, I noticed something at the end...

} // end function

It seems that classPicked may be declared within a function (although no function is visible in the provided code). Since it is confined to function scope, any attempts to access it from outside will fail.

To resolve this issue, move the declaration of classPicked outside of the function.

var classPicked = Array(1);

function thisusesclasspicked() {
  ...

Additionally, please ensure proper indentation of your code for improved readability and maintenance.

LATEST UPDATE FROM COMMENTS:

After further examination, I located the declaration...

classPicked = Array(l);   
for (var i = 0; i < l; ++i) {
  classPicked[i] = chosenClass[i].split(', ').reverse().join(' ');
  showText += classPicked[i]+ '<br>';
}

...however, you are resetting the array with a single element just before making changes to it... You essentially empty it here: classPicked = Array(l);

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

Redux persist isn't functioning properly as the rehydration process only happens one time

I am currently working with React version 15.4.2 and Redux, trying to persist my React/Redux state when the browser refreshes. Despite suggestions of using redux-persist, I encountered issues when following the basic instructions as the state resets to emp ...

How to find a matching array in MongoDB collections

Is there a way to find documents in my MongoDB collection that have similar arrays and order them by their similarity value? For example: If I search for {chars:['a', 'b', 'c']} And the stored documents are: 1. {chars:[&ap ...

Execute a function upon pressing the enter key

Currently, I am working on coding a webpage with a form that includes one field where users input a set of numbers. After typing in the numbers, they should then press a button labeled 'Run' to execute the code. However, the issue arises when use ...

Retrieve information based on the class

I've been struggling for hours trying to find a solution. Here's a simplified version of my code: PHP : foreach($db->query("SELECT id FROM news ORDER BY position ASC") as $row) { ... <input type="text" class="_title" > ...

An array devoid of elements may still hold significance

I have a specific function structure as follows: public returnData(): { points: Array<{ x: number, y: number }>, pointsCount: Array<number> } { return { points: [{x: 0, y: 1},{x: 1, y: 2 }], pointsCount: [1, 2, 3, 4] } ...

Automatically disconnect from the application upon logging out of Google account

I've successfully set up an express server that uses Google OAuth for user authentication. One interesting challenge I'm facing is how to handle the scenario where a user logs out of Google services (like Gmail) and automatically log them out fro ...

Issue in C Programming: Unable to convert parameter to int*

Hello everyone, I'm a newcomer here and have a question regarding my C Programming Assignment on Procedure and Struct. My assignment involves declaring an Array of a Struct and then setting it as an alias. Here's the code snippet that I've ...

jqgrid's date restriction is set to November 30th, 1999 at midnight

I have a table displaying DATETIME values. However, after editing the datetime value, it always changes to "1999-11-30 00:00:00", both in jqgrid and the database, regardless of the date entered. [Tue Mar 12 11:39:28 2013] [error] [client 171.43.1.4] PHP N ...

Switching between PascalCase and camelCase in TypeScript leads to unexpected behavior

Currently, I am in the process of transitioning a C# desktop application to an Angular/TypeScript web application. In the C# application, all class properties are named using PascalCase. Therefore, I decided to maintain this naming convention in the TypeS ...

Click functionality being incorporated into Material UI

I need assistance with incorporating an onClick event handler in a material ui example, but it doesn't seem to be working as expected. <Tooltip title="Filter list"> <IconButton aria-label="Filter list"> <FilterListIcon/> </ ...

Dynamic Wave Effects with jQuery

I'm interested in developing an interactive animation where waves emanate from a central point and trigger similar waves of varying sizes at outer nodes in a circular pattern. After researching, I came across a few libraries: https://github.com/mbos ...

Deploying a single node.js app on two separate servers and running them simultaneously

Is it possible to set up my game to run on both the west coast and east coast servers, while still using the same domain? In my code structure, app.js runs on the server with the home route serving as the entry point for the game. This means that users si ...

Is it possible to loop an animation every time the text within the element is altered?

I have an issue with my HTML text element that triggers an animation on page load. I am attempting to write a script that changes the original text to a new one and replays the animation. Here is a snippet of my code: setTimeout(function typewriter() { ...

Ways to serve JSON response following a 400 error code

After a user submits incorrect form details, such as an invalid username or blank email address, I make an Ajax request to my REST API. The response data I receive is structured as follows: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: applicati ...

Building Dynamic Props in Vue.js using v-select Component

I am utilizing a chart that relies on properties for data. <template> <v-row> <v-col col="12" sm="12"> <Chart :data="series2"></Chart> ### This chart receives the props < ...

The change() function isn't being called in the FooterControl of the nested Gridview

In my gridview, there is a nested structure with a footer row for inserting data. When the parent row expands, the footer controls are generated. There are two dropdowns where the second dropdown's options depend on the selection in the first dropdown ...

Guide to building interactive dropdown menus in Angular 8

In my user interface, each row contains three dropdowns for level 1, level 2, and level 3, as well as an "Add Level" button. When the "Add Level" button is clicked, a new set of three dropdowns for level 1, level 2, and level 3 should be added dynamically ...

What is the best way to use jQuery to insert this block of HTML into a page from a JSON response?

<script type="text/javascript"> var dataString2 = 'run=captchagood&comment=' + comment; $.ajax({ type: "POST", url: "process.php", data: dataString2, dataType: "json", error: 'error', success: function ...

Guide to Incorporating a Marker into an SVG Blinking Rectangular or Circular Border Image on Google Maps

I have a link that points to a specific location on Google Maps using latitude and longitude: http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png Now, I am looking to add a blinking border to this marker link. Is there a way to achieve this ...

Reading an array from a file using PHP

Is there a way to successfully read a JSON array and add/merge a new element to it? My data.json file contains the following array: [["2015-11-24 18:54:28",177],["2015-11-24 19:54:28",178]] Here is an example of a new element array: Array ( [0] => A ...