javascript - 函数内 .push 后全局数组未更新

标签 javascript arrays push global

大家好,谁能帮帮我? 基本上我想制作一个突发新闻页脚,循环遍历 newsWire 数组并自动更新文本。问题是,当我在 loadNewswire 函数外部运行 console.log(newsWire.length) 时,它返回 0,而内部的 console.log 返回 40,因为它应该是这样?

链接:http://jsfiddle.net/u8y8zh72/3/

<html>
<head>
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <style>
        footer {
            height: 75px;
            position: fixed;
            bottom: 0;
        }
    </style>
</head>
<body>
    <div class="container">
    <ul id="js-news" class="js-hidden"></ul>
    </div>
    <footer>
        <div class="container" id="newswiretxt">
        <span></span>
        </div>
    </footer>
</body>
<script type="text/javascript">
    var newsWire = [];
    function loadNewswire() {
        $.getJSON('http://api.nytimes.com/svc/news/v3/content/all/all.json',
        {'api-key': 'XXXXXXXXX'},
        function(data) {
            console.log(data)
            var newsWireTemp = [];
            for (var i = 0; i < data.results.length; i++) {
                var breakingNews = data.results[i];
                var breakingTitle = breakingNews.title;
                var breakingAbstract = breakingNews.abstract;
                newsWireTemp.push(breakingTitle);
                newsWireTemp.push(breakingAbstract);
            }
            newsWire = newsWireTemp;
            console.log(newsWire.length);
        });
    }
    loadNewswire();
    console.log(newsWire.length);


    $(document).ready(function() {
    var items = newsWire;
    $text = $('#newswiretxt span'),
    delay = 10; //seconds
    function loop (delay) {
        $.each(items, function (i, elm){
            $text.delay(delay*1E3).fadeOut();
            $text.queue(function(){
                $text.html(items[i]);
                $text.dequeue();
            });
            $text.fadeIn();
            $text.queue(function(){
                if (i == items.length -1) {
                    loop(delay);   
                }
            $text.dequeue();
            });
        });
    }
    loop(delay);
    });
</script>

最佳答案

最主要的是:

...
loadNewswire();
console.log(newsWire.length);
...

当您调用 loadNewsWire 时,您将启动异步 JSON 请求。但是,脚本执行不会等待该函数完成,因此它会立即运行以下 console.log 语句。此时,JSON 请求尚未完成,因此 newsWire 数组仍为空 - 这就是 console.log(newsWire.length) 返回 0 的原因。

在您的 loadNewsWire 函数中,您有一个回调函数,当 JSON 请求返回您的数据时,该函数将被执行。此时,您正在填充数组,console.log(newsWire.length) 会为您提供预期的计数。

<小时/>

针对评论进行更新:

Is there anyway to make the rest of my code wait for the function to execute?

是的! $.getJSON$.ajax 的便捷包装器,它返回一个 jqXHR 对象(完整的有趣细节在 jQuery documentation 中)。您可以向该对象添加其他回调,这就是您在调用 $.getJSON 时实际执行的内联操作。以下内容:

$.getJSON('http://...', { 'api-key': '...' },
    function (data) {
        // stuff
    });

相当于:

$.getJSON('http://...', { 'api-key': '...' })
    .done(function (data) {
        // stuff
    });

因此,如果您修改 loadNewswire 以返回从 $.getJSON 返回的对象,则可以向其附加一个回调,该回调将等待异步操作完成,并将其余代码放入其中。如果您将代码更改为:

function loadNewswire() {
    return $.getJSON(
        ...
    );
};

然后,您可以使用 donefailalways 回调之一包装您想要等待的代码。

您的调用代码将如下所示:

loadNewswire().done(function () {
    console.log(newsWire.length);
    // and any other code you want to hold until the async operation is complete
});

我建议阅读 previously mentioned documentation - 它有点繁重,但它很好地概述了如何使用 jQuery 处理异步请求。

关于javascript - 函数内 .push 后全局数组未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33612259/

相关文章:

javascript - jQuery 的 getScript() 回调是否不可靠或者我做错了什么?

c - 将过去用户输入的命令存储到链接列表中

javascript - 二叉堆 - 为什么删除函数需要调用 bubbleUp 方法?

xcode - 捆绑标识符和推送证书... aps-环境授权错误

c++ - 临时住址?

javascript - 如何无限循环动画js

javascript - Mobx + React 不会更新渲染的组件

javascript - 如何使用 servlet 和 jsp 在浏览器上播放视频..并且视频存储在本地系统中,如 D :/video/sample. mp4

javascript - 将项目插入二维数组

c - C中二维数组的段错误