全局数组在.push内部函数后没有更新

时间:2015-11-09 15:16:13

标签: 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>

1 个答案:

答案 0 :(得分:0)

主要的是:

loadNewsWire

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

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

更新以回复评论:

  

无论如何都要让我的其余代码等待函数   执行?

是的! $.ajaxjqXHR的便捷包装器,它返回$.getJSON个对象(jQuery documentation中的完整多汁细节)。您可以向该对象添加其他回调,这是您在调用$.getJSON('http://...', { 'api-key': '...' }, function (data) { // stuff }); 时实际内联的内容。以下内容:

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

相当于:

loadNewswire

因此,如果您修改$.getJSON以返回从function loadNewswire() { return $.getJSON( ... ); }; 返回的对象,则可以附加一个回调函数来等待异步操作完成,并放置其余代码在里面。如果您将代码更改为:

done

然后,您可以使用failalwaysloadNewswire().done(function () { console.log(newsWire.length); // and any other code you want to hold until the async operation is complete }); 回调之一来包装您要等待的代码。

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

$_POST

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

相关问题