Javascript - 值存在,然后消失,然后再次出现?

发布于 2024-11-14 17:40:41 字数 725 浏览 3 评论 0原文

这让我抓狂。我也无法通过 Firebug 解决这个问题。有人可以解释一下这是怎么回事吗?

基本上我有一个传入的文本文件,其中每一行都包含一个以竖线分隔的记录。我将它们分成字符串数组的数组,以便稍后在自动完成文本框中使用。代码如下:

<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 为空...但第三个再次显示所有数据。删除第一个健全性检查不会影响第二个和第三个。

这怎么可能?为什么会这样呢?这让我发疯。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

逆光下的微笑 2024-11-21 17:40:41

您忘记了 get() 函数是一个异步函数。您在其中定义的回调仅在文件加载后才会被调用。本质上,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文