![](/img/trans.png)
[英]How to access a variable defined in a react component from another js file?
[英]How to access js array defined in another js file
如何访问在另一个 JavaScript 文件中定义的 JavaScript 数组?
如果变量是全局变量,并且您首先在 HTML 文件中包含带有变量的 JS 文件,则可以通过第二个 JS 文件访问它:
<script type="text/javascript" src="somefile_with_variable.js"/>
<script type="text/javascript" src="somefile_reading_variable.js"/>
在浏览器中,所有 .js 文件共享同一个全局空间。 只需按名称引用它。
在某个页面上包含这两个文件,您可以通过其名称正常访问该数组。
为了使其工作,将您的数组定义为“var”(全局变量)。 转到数组所在的 JS 文件并导出它。
var globalArray;
export{globalArray, otherFunctionsYouExport};
现在转到要访问数组的 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.