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
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.
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
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.
- Example works fine in my tests. Your original question had "New" instead of "new" which didn't work – dtech Commented Apr 9, 2012 at 17:16
- @dtech he is loading the first script asynchronously. that is his problem, see my answer – Alex Commented Apr 9, 2012 at 17:17
- @Zee Tee, You should put together a fiddle. – Alexander Commented Apr 9, 2012 at 17:19
- @Zee Tee complete your question beforehand and don't edit/add so much afterwards, a lot of initial answers and comments look dumb or are incorrect because your current question looks nothing like your original question. – dtech Commented Apr 9, 2012 at 17:22
- @dtech question was the same, code is a bit different (more clear). – Control Freak Commented Apr 9, 2012 at 17:24
4 Answers
Reset to default 10New
is not a keyword.
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.
Since you haven't posted the asynchronous code I am not going to provide a callback
sample. Though, a quick solution follows:
var interval = setInterval(function(){
if(data) {
/* ... use data ... */
clearInterval(interval);
}
}, 500);
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.
So, zz = 1
is actually 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);
If you're using jQuery, perhaps you should try .getScript()
rather than 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
});
<script>
data = [];
data[0] = 'hi';
data[1] = 'bye';
</script>
<script>
alert(data[0]);
</script>
use this, remove var makes variable global