javascript 如何访问另一个js文件中定义的js数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5242050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to access js array defined in another js file
提问by Deepa
how i can access an javascript array which is defined in another javascript file
我如何访问在另一个 javascript 文件中定义的 javascript 数组
回答by Dolan Antenucci
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:
如果变量是全局变量,并且您首先在 HTML 文件中包含带有变量的 JS 文件,则可以通过第二个 JS 文件访问它:
<script type="text/javascript" src="somefile_with_variable.js"/>
<script type="text/javascript" src="somefile_reading_variable.js"/>
回答by Malvolio
Inside a browser, all the .js files share the same global space. Just refer to it by name.
在浏览器中,所有 .js 文件共享同一个全局空间。只需按名称引用它。
回答by Ghyath Serhal
Include both files on a certain page and you can access the array normally by its name.
在某个页面上包含这两个文件,您可以通过其名称正常访问该数组。
回答by Shiran .Y.
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”(全局变量)。转到数组所在的JS文件并导出它。
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.
现在转到要访问数组的 JS 文件并导入全局数组。如果您有多个函数要导入,请使用 * 它将导出上面括号之间的所有内容。
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

