Accessing an array within a function from a separate .JS file

Currently, I am facing a somewhat awkward predicament where I have a function in main.js that requires an array that is populated in second.js...

In simple terms, the function in main.js is designed to be reusable:

function chug()
{
    p1.innerHTML = st_a[0];
    p2.innerHTML = st_a[1];
    ...
}

The variable 'st_a' is meant to be interpreted as: st_ + , with 'a' being the specific variable in this scenario. The concept is that the second.js file will contain multiple arrays (st_a, st_b, etc.) and depending on the requirement, the corresponding array will be used to fill the paragraph elements (p1, p2, etc.)

Any suggestions on how to tackle this situation?

Answer №1

In case st_[x] serves as a global variable, you have the option of referencing it using window['st_a']. Therefore, you should be able to implement something similar to:

function chug()
{
    var arrid = 'st_'+'a';
    p1.innerHTML = window[arrid][0];
    p2.innerHTML = window[arrid][1];
    //...
}

Alternatively, you can utilize a function to fetch the array:

function getArr(id){
  return window['st_'+id];
}

Alternatively, you could create a container object in second.js with a 'get' method, similar to:

var myArrays = {
  st_a: [],
  st_b: [],
  st_c: [],
  get: function(id){
    return this['st_'+id];
  }
  /* etc */
}

Subsequently, chug could resemble:

function chug()
{
    var arr = myArray.get('a');
    p1.innerHTML = arr[0];
    p2.innerHTML = arr[1];
    //...
}

Answer №2

Avoiding the use of global variables is crucial in programming. When global variables are used, there is a risk of inadvertently overriding previously set variables without any warning from JavaScript.

There are several alternatives to utilizing global variables:

  • One approach is to encapsulate all functions within a single object. Here is an example:

    var MYAPP = {} MYAPP.chug = function() { // Your code } // Then, in any subsequent file, you can continue adding functions to MYAPP: MYAPP.anotherFunction = function() {} // And call functions like this: MYAPP.chug()

By taking this approach, you only introduce one variable into the global scope.

  • Another option is to implement a library like Require.js.

To address this issue, you can apply the following modifications based on your chosen solution:

// Using a snippet from kooiinc
MYAPP.myArrays = {
   st_a: [],
   st_b: [],
   st_c: [],
   get: function(id){
       return this['st_'+id];
   }
   /* etc */
}
MYAPP.chug = function() {
    var arr = this.myArrays.get('a') // 'this' here refers to the MYAPP object
    p1.innerHTML = arr[0]
    // ...
}

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 a 400 Bad Request Error in Node.js and Express for a

It seems like I must be making a silly mistake, because this should be a simple task. All I want to do is send a POST request in an Express route. This is my app.js: var express = require('express'); var path = require('path'); var f ...

When attempting to swap out ":customimage:" with an image in a React.js HTML view, the result displayed is [object Object]

I have created a function below: WordColonsToImage(comment) { var newcomment = comment.replace(/:wave:\s*/g, <img src={wavinghand} />) return newcomment } Here is an example: WordColonsToImage("Hi! :wave:") whi ...

What are the steps to effectively utilize the $filter('filter') function when filtering multiple columns with OR as the condition?

In my AngularJs Application, I have a collection of customers. var customers = [ { "Name": "Alfreds Futterkiste", "City": "Berlin", "Country": "Germany" }, { "Name": "Ana Trujillo Emparedados y helados", ...

Is there a way to retrieve JSON data from a specific URL and assign it to a constant variable in a React application?

I am exploring react-table and still getting the hang of using react. Currently, in the provided code snippet, a local JSON file (MOCK_DATA.json) is being passed into the const data. I want to swap out the local JSON with data fetched from a URL. How can ...

Exploring nested list iteration in Python

I have a total of 43 items, each consisting of 75 data points. These 75 points represent different times of the day, and I am looking to calculate the standard deviation of each specific time across all 43 items. I attempted to use a nested for loop, but i ...

Tally up the occurrences of each item in the array and provide the result in the form

Is there a built-in method in JavaScript to convert an array like: const colorArray = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black']; into an object that c ...

Leveraging body-parser for capturing an indefinite amount of text fields in node/express

Background In pursuit of my Free Code Camp back end certification, I am embarking on the task of creating a voting application. For detailed information and user stories required for this project, visit this link: Among the user stories is the ability to ...

Automatically choosing a radio button in a carousel using Angular

My Angular application includes the npm-hm-carousel. I am looking to automatically select the item in the center of the carousel, similar to the image provided. However, I also need to bind one of the ids to the selected item as I scroll through the carous ...

Accessing a specific child div within a parent div using JavaScript and CSS

Struggling to target and modify the style of the child div within id="videoContainer" <div id="videoContainer"> <div style="width: 640px; height: 360px"> <------- this is the target <video src ...

The pagination feature for Swiper is experiencing issues across both desktop and mobile platforms

I am having an issue with the pagination display in the text. I would like it to appear below the text as a standalone item for better visibility. Another problem arises when viewing the page on mobile devices - the hamburger menu displays behind the slid ...

Access the most recent state value with React's Context API

Trying out the React context API, Take a look at the someComponent function where I pass the click event (updateName function) to update the value of state.name from the GlobalProvider function. After updating state.name, it reflects in the browser but t ...

How to access the parent array element in a nested ng-repeat in AngularJS

Hey there, I'm facing a bit of a puzzle with a seemingly simple question that's got me stumped. In my code, I have a nested array structure: $scope.rootItem = { id: '1', type: 'course', title: ' ...

Unable to locate xpath during the second iteration or attempt

As a newcomer and hobbyist programmer, I have hit a wall with this particular issue. My goal is to loop through a website and extract data to print. While my code successfully retrieves data from the first link, I am struggling to make it "click" on the se ...

Update: Cannot mark as invalid a nested document that has not been included in an array

I recently encountered an issue with my upsert query in mongoose. It was functioning perfectly in version 3.8, but ever since I upgraded to version 4, I've been facing the following error: Unable to invalidate a subdocument that has not been added to ...

Tips for incorporating a Survey Monkey website embed into an Angular application

I have a Survey Monkey account with multiple surveys. I am trying to embed a survey from this website into my Angular website, which already has Bootstrap and jQuery added. I attempted to directly add the script in an HTML component, but it did not work. ...

Displaying the saved MTRC (markdown-to-react-components) content from the database

I currently have data stored in a database that has been produced using the markdown-to-react-components package as MTRC(content).tree What is the best way to render this content? I've experimented with various approaches, such as dangerouslyInsertHT ...

Steps for extracting URL parameters from AWS API Gateway and passing them to a lambda function

After successfully setting up my API gateway and connecting it to my lambda function, I specified the URL as {id} with the intention of passing this parameter into the lambda. Despite numerous attempts using both the default template and a custom one for ...

Multiple card displays not working with Javascript Fetch API

I wrote a script that retrieves data from a URL and then organizes it into tables for display to the user. Initially, the script functioned correctly. However, I decided to enhance its flexibility by introducing two parameters - name and HTML div name wher ...

What is the best way to target and focus on all class fields that have a blank value?

<input type ="text" class="searchskill" value=""> <input type ="text" class="searchskill" value="3"> <input type ="text" class="searchskill" value=""> <input type ="text" class="searchskill" value="4"> Is there a way to target o ...

What is the best way to invoke a Javascript function within the same file using PHP?

I am facing an issue with my PHP file named "PhpCallJavascript". I am attempting to call the function CreateSVG() from within the PHP code. However, it seems that it is not working. Do I need to incorporate AJAX here? Or perhaps there is another solutio ...