Javascript 如何定义全局数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10076873/
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 define Global Arrays?
提问by Control Freak
Code example:
代码示例:
<script>
var data = new Array();
data[0] = 'hi';
data[1] = 'bye';
</script>
<script>
alert(data[0]);
</script>
This gives the following error: data is not defined
这给出了以下错误: data is not defined
How do you make something like this work? Especially if the first <script>
block is being loaded on the page by ajax, and the second block is working from it. jQuery solution is acceptable.
你怎么做这样的工作?特别是如果第一个<script>
块被 ajax 加载到页面上,而第二个块正在从它工作。jQuery 解决方案是可以接受的。
回答by xandercoded
New
is not a keyword.
New
不是关键字。
Use:
用:
var data = new Array();
Or, more succinctly:
或者,更简洁地说:
var data = [];
After your edit you mention that the first script block is loaded asynchronously. Your code will not work as written. data
is a global variable, once it is loaded onto the page. You need to use a callback pattern to properly execute the code.
编辑后,您提到第一个脚本块是异步加载的。您的代码将无法正常工作。data
是一个全局变量,一旦它被加载到页面上。您需要使用回调模式来正确执行代码。
Since you haven't posted the asynchronous code I am not going to provide a callback
sample. Though, a quick solution follows:
由于您尚未发布异步代码,因此我不打算提供callback
示例。不过,一个快速的解决方案如下:
var interval = setInterval(function(){
if(data) {
/* ... use data ... */
clearInterval(interval);
}
}, 500);
回答by Kristian
To create a global variable, just omit 'var' from the statement. When you omit 'var', you're actually creating the variable in the window namespace.
要创建全局变量,只需从语句中省略 'var'。当您省略“var”时,您实际上是在窗口命名空间中创建变量。
So, zz = 1
is actually window.zz = 1
所以,zz = 1
实际上是window.zz = 1
If you really wanted to, you could explicitly say
如果你真的想,你可以明确地说
window.data = new Array(); //remember that new should be lowercase.
But you can write that faster anyway by saying
但是你可以通过说更快地写
data = ['hi','bye'];
alert(data);
回答by Scott Sauyet
If you're using jQuery, perhaps you should try .getScript()
rather than using .html()
;
如果您正在使用 jQuery,也许您应该尝试.getScript()
而不是使用.html()
;
// in separate file
data[0] = 'hi';
data[1] = 'bye';
// in main file
var data = [];
$.getScript(url).done(function() {
alert(data[0]);
}).fail(function() {
// handle error
});