设置变量导致的功能作用很奇怪 [英] Setting variable to result of function acting very strange

查看:152
本文介绍了设置变量导致的功能作用很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript函数,应该返回所有维基百科页面链接到文章的数组,给出的标题。

I have a function in javascript that is supposed to return an array of all the articles linked to by a wikipedia page, given the title.

下面是:

function getLinksFrom(title, returnArray, plcontinue) {
  var url = 'http://en.wikipedia.org/w/api.php?action=query&prop=links&titles=' + title + '&format=json&pllimit=500&plnamespace=0&callback=?';
  if (!returnArray) {
      returnArray = [];
  }
  if (!plcontinue) {
    plcontinue = '';
  }
  if (returnArray.length === 0 || plcontinue !== '') {
      if (plcontinue !== '') {
          url = 'http://en.wikipedia.org/w/api.php?action=query&prop=links&titles=' + title + '&format=json&pllimit=500&plnamespace=0&plcontinue=' + plcontinue + '&callback=?';
      }
      $.ajax({url: url, 
          dataType: 'json',
          async: false,
          success: function(data) {
              for (key in data['query']['pages']) {
                  links = data['query']['pages'][key]['links'];
              }
              for (var i = 0; i < links.length; i += 1) {
                  returnArray.push(links[i]['title']);
              }
              if (data.hasOwnProperty('query-continue')) {
                  plcontinue = data['query-continue']['links']['plcontinue'];
              } else {
                  plcontinue = '';
              }
              console.log(returnArray);
              return getLinksFrom(title, returnArray, plcontinue);
          }
      });
  }
  console.log(returnArray);
  return returnArray;
}

当我运行这个功能,看控制台中,执行console.log(returnArray);线把我想在控制台中。字符串数组。但在这里,我感到困惑。

When I run this function and watch the console, the console.log(returnArray); lines put what I want in the console. Arrays of strings. But here's where I get confused.

欲存储returnArray,在可变称为链路。下面是一个线,这是了以下功能。

I want to store that returnArray, in a variable called links. Here's that line, which is below the function.

var links = getLinksFrom('United States');

但链接不会结束等于被记录之前那个美妙的事情。相反,它包含对象的数组,即不正确的长度。

But links doesn't end up equalling that wonderful thing that was logged before. Instead, it contains an array of objects, that isn't the right length.

这里发生了什么?

推荐答案

由于 getLinksFrom 是异步函数,当JS求函数调用它写到导致的链接变量。但在这一点上的时间 returnArray 是空的!

Since getLinksFrom is asynchronous function, when JS evaluates function call it writes result to the links variable immediately. But at that point of time returnArray is empty!

看看图片:

这表明,按向 returnArray 变量,而最有可能分配给链接后会发生,后使用这个变量。

It shows that pushing to the returnArray happens after assigning it to the links variable and, most likely, after using this variable.

所以,如果你使用异步code,你cant't只是做 A = B()。通常在这种情况下,人们使用回调: B(函数(){/ *做一些带有* /})(参数是怎样的一个成功的功能)。所以,你应该重写你的code。使用异步回调的工作。

So if you use asynchronous code, you cant't just do a = b(). Usually in this case people use callbacks: b(function(a) { /* do something with a */ }) (argument is kind of a "success" function). So you should rewrite your code to work asynchronously using callbacks.

但是,还有一个问题,你code:你永远不会停止自我调用。每个全成请求后您发送另一个永不止步。也许,几次要求后woun't得到任何有用的数据了,何必远程服务器和用户的无用请求网络?当你完成干脆不要做递归。相反的,你可以调用回调来通知您的调用函数,你就大功告成了。

But there is one more problem with you code: you never stop self-calls. After every successfull request you send another and never stop. Maybe, after several requests you woun't get any usefull data anymore, so why bother remote server and user's network with useless requests? Just don't do recursion when you're done. Instead of that you can call callback to inform your function caller that you're done.

这篇关于设置变量导致的功能作用很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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