开发者

How to access js array defined in another js file

How do I access a JavaScript array that is defined in 开发者_StackOverflow中文版another JavaScript file?


If the variable is global, and you include the JS file with the variable first in your HTML file, then it is accessible via the second JS file:

<script type="text/javascript" src="somefile_with_variable.js"/>
<script type="text/javascript" src="somefile_reading_variable.js"/>


Inside a browser, all the .js files share the same global space. Just refer to it by name.


Include both files on a certain page and you can access the array normally by its name.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜