Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access js array defined in another js file

How do I access a JavaScript array that is defined in another JavaScript file?

like image 350
Deepa Avatar asked Mar 09 '11 06:03

Deepa


People also ask

How do you access the data of one JS file to another?

In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting.

Can I import a JS file into another JS file?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.

How do you link an array in JavaScript?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays.


1 Answers

In order for this to work define your array as "var" (global variable). Go to the JS file where the array is and export it.

var globalArray;

export{globalArray, otherFunctionsYouExport};

Now go to the JS file you want the access to the array and import the global array. If you have multiple functions to import, use * and it will export everything between the brackets above.

import * as chooseName from './path of your JS file you export from';

// to use it write this
chooseName.globalArray // put here the rest of your code
like image 186
Shiran .Y. Avatar answered Sep 29 '22 19:09

Shiran .Y.