Javascript - 值存在,然后消失,然后再次出现? [英] Javascript - value exists, then disappears, then appears again?

查看:130
本文介绍了Javascript - 值存在,然后消失,然后再次出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我疯了。我也无法通过Firebug来解决这个问题。有人可以解释这里发生了什么吗?

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

对于某些人第一次完整性检查工作正常的原因 - 它显示我所期望的所有数据。第二个显示rawData为空...但第三个显示所有数据。删除第一个健全性检查不会影响第二和第三。

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.

推荐答案

您忘记了get()函数是一个异步函数。您定义的回调只有在加载文件后才会调用inside。本质上,JavaScript解释器将其放入队列中,以便在操作完成时准备好,然后允许其余代码执行。

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.

这篇关于Javascript - 值存在,然后消失,然后再次出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆