繁体   English   中英

如何在.getScript中使用另一个Javascript文件中的变量?

[英]How to use variable from another Javascript file with .getScript?

我有两个JavaScript文件,其中一个具有内部数组。 我想使用从一个文件到另一个文件的数组,但不能。 我尝试使用.getScript,但它仅在函数内部更改。 我怎么解决这个问题?

我尝试使用$ .getScript,但是没有用。 它只更改函数内部的内容,但我想获取变量并在函数外部使用。

array.js

array = ['a', 'b', 'c'];

main.js

var myArray = [];

$.getScript('array.js', function (){
    window.myArray = array;
    console.log(myArray); //it print out ['a', 'b', 'c']
}

console.log(myArray); //it print out []

我希望myArray与另一个文件中的['a', 'b', 'c'] array具有相同的值,但是当我在函数外部使用时,它仍然没有改变。

先感谢您 :)

这里的问题是$.getScript异步运行,这意味着console.log(myArray)$.getScript可以完成之前执行。您需要等待它完成。

$.getScript('array.js').then(function(){
    console.log(array);
    console.log(window.array);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM