Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  123] [ 5]  / answers: 1 / hits: 71037  / 12 Years ago, mon, april 9, 2012, 12:00:00

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.


More From » jquery

 Answers
175

New 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);

[#86356] Friday, April 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarettajb

Total Points: 678
Total Questions: 94
Total Answers: 90

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;