【问题标题】:Why isn't my function returning my array? [duplicate]为什么我的函数不返回我的数组? [复制]
【发布时间】:2016-10-02 08:38:41
【问题描述】:
function getContent(type) {
  var content = [];
  $.get(`/${type}.json`, function(data) {
    $.each(data, function(index, hash) {
      content.push(hash);
    });
    // 1. content = [object, object, etc..]
  });
  // 2. content = []
  return content;
}

我需要帮助来理解这一点。为什么content 在第二条评论中为空?从外观上看,该函数开始将哈希推入一个名为 content 的新变量中,而不是引用我在开始时明确创建的内容。我该如何解决?为什么 javascript 范围如此混乱。

另外,为了解决这个问题,我使用全局变量。为什么我的函数可以在函数的任何位置访问全局变量content,但在开始函数中调用content,它将无法访问某些地方。

【问题讨论】:

    标签: javascript jquery arrays scope


    【解决方案1】:

    因为$.get 是异步的。这个调用的本质是它进入事件循环并且不会修改你当前的程序流程。

    你应该使用回调。

    function getContent(type, callback) {
      var content = [];
      $.get(`/${type}.json`, function(data) {
        $.each(data, function(index, hash) {
          content.push(hash);
        });
        callback( content );
     });
    }
    
    getContent("items", function( content ) {
       console.log(content);
    });
    

    为了给你一个更好的例子,你也可以使用你的流程,但它应该看起来像这样:

    function getContent(type, callback) {
      var content = [];
      $.get(`/${type}.json`, function(data) {
        $.each(data, function(index, hash) {
          content.push(hash);
        });
        callback();
      });
      return content;
    }
    
    var items = getContent("items", function() {
       console.log( items );
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多