Javascript - value exists, then disappears, then appears again?
This is driving me nuts. I can't work it out stepping through with Firebug either. Can someone please explain what is going on here?
Basically I have an incoming text file where each line contains a pipe-delimited record. I'm splitting these into an array of array of string for later use in an autocomplete textbox. The code is as follows:
<script type="text/javascript">
$(function () {
var rawData = new Array();
开发者_运维技巧 $.get("/sample.txt",
function (data) {
var raw = data.split('\n');
for (var i = 0; i < raw.length; i++) {
rawData.push(raw[i].split('|'));
};
alert(rawData); // 1st sanity check
}
);
alert(rawData); // 2nd sanity check
alert(rawData); // 3rd sanity check
For some reason the first sanity check works fine - it displays all the data as I'd expect. The second one displays that rawData is empty... but the 3rd one shows all of the data again. Removing the 1st sanity check doesn't affect the 2nd and 3rd.
How is this possible? Why is this so? This is driving me crazy.
You are forgetting that the get() function is an asynchronous function. The callback you define inside will only get called once the file is loaded. In essence, the JavaScript interpreter puts it in a queue ready for when the action completes, and then allows the rest of the code to execute.
So, your alert in the callback will reflect the fact that the file was loaded. The alerts outside will execute well before that file is loaded. Of course, the longer you personally wait to dismiss the second alert, the better the change that the third alert will execute when all the data is loaded.
精彩评论