How do I define global arrays?
Sample code:
<script>
var data = new Array();
data[0] = 'hi';
data[1] = 'bye';
</script>
<script>
alert(data[0]);
</script>
This results in the following error: data is not defined
How do you make something like this work? Especially if the first block is <script>
loaded onto the page using ajax and the second block works with it. JQuery's solution is acceptable.
source to share
New
is not a keyword.
Using:
var data = new Array();
Or, more succinctly:
var data = [];
After editing, you will notice that the first script block is loaded asynchronously. Your code will not work as written. data
- a global variable when it is loaded onto the page. You need to use a callback pattern for the code to execute correctly.
Since you haven't posted asynchronous code, I'm not going to provide a sample callback
. A quick solution follows though:
var interval = setInterval(function(){
if(data) {
/* ... use data ... */
clearInterval(interval);
}
}, 500);
source to share
To create a global variable, just omit 'var' from the statement. When you omit "var", you are actually creating a variable in the window's namespace.
So zz = 1
actuallywindow.zz = 1
If you really wanted it, you could directly say
window.data = new Array(); //remember that new should be lowercase.
But you can write that it's faster anyway by saying
data = ['hi','bye'];
alert(data);
source to share
If you are using jQuery, perhaps you should try .getScript()
instead of using .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
});
source to share