【问题标题】:unable to read values into global array variable using javascript无法使用 javascript 将值读入全局数组变量
【发布时间】:2013-10-17 02:53:28
【问题描述】:

我正在编写如下所示的 javascript 代码。我只是先展示代码的基本骨架。

var array = [];

function mainFun()
{
     A();
}
function A()
{
    //some code
    B();
    //code to print all values in "array"
}

function B()
{
    C();
}

function C()
{
     //some code
     //push elements one by one in "array"
     for (var i=0; i<10; i++)
     {
           array.push(i); //something on these lines
     }
}

我知道这段代码看起来很奇怪,但这正是我正在处理的情况。由于 Javascript 的函数级范围(与常规块级范围不同),我无法访问和打印A() 中已推送到C() 数组中的所有元素。那么如何让我的数组变量像真正的全局变量一样工作,并且知道将哪些元素推入其中?

好的,这是我的原始源代码(虽然我不知道虚拟代码是如何工作的!)

var allLinks = {}; //set of all internal and external links
var Queued = [];
var crawlingURL;
var Crawled = [];
var xmlHttp = null, originURL, maxHops = 0, currentHop = 0;

function changeText(){
    var tabID, sourceURL;
    chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
        console.log(tabs[0].url);
        document.getElementById('URL').innerHTML="URL of Current Page : "+tabs[0].url;
        tabID = tabs[0].id;
        sourceURL = tabs[0].url;

        Queued.push(sourceURL); //push the origin link the Queued array to begin crawling
        beginCrawl(sourceURL);
    });
}

document.addEventListener('DOMContentLoaded', function () {
    changeText();
});

function beginCrawl(url)
{
    originURL = url;
    maxHops = 2;
    currentHop = 1;
    var queueIndex = 0;
    //httpGet(originURL);
    while(queueIndex<1) //(currentHop <= maxHops)
    {
        crawlingURL = Queued[queueIndex];
        //allPages[crawlingURL] = {url:url, state:"crawling", level:0, host:startingHost};
        httpGet(crawlingURL);
        Crawled.push(crawlingURL);
        queueIndex++;

        for(var j = 0; j < Queued.length; j++)
        {
            console.log(j+". "+Queued[j]+"\n");
        }
    }
}
function httpGet(theUrl)
{
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, true );
    xmlHttp.send( null );
    xmlHttp.onreadystatechange = ProcessRequest;
}

function ProcessRequest()
{
    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) // xmlHTTP success
    {           
            var container = document.createElement("p");
            container.innerHTML = xmlHttp.responseText;
            var anchors = container.getElementsByTagName("a");
            var list = [];
            for (var i = 0; i < anchors.length; i++) 
            {
                var href = anchors[i].href;
                var exists = 0;

                // to check for duplicate entries in the list
                    for(var j = 0; j < Queued.length; j++)  // remove duplicates
                        if(Queued[j] == href)
                            exists = 1;
                    if (exists == 0)
                    {
                        Queued.push(href);
                        document.getElementById('printORGLinks').innerHTML += href + "<br />";
                    }
            }
        }
}

我无法打印队列数组中的值! (您可能理解,这是某种网络爬虫的初步代码。我需要获取推入 Queued 数组的所有 URL 的列表)。

【问题讨论】:

  • 你到底在问什么?您的 array 变量是全局变量,因此您可以在任何地方访问它。
  • 您的代码运行良好。
  • 将新值推送到数组的部分是否存在于 AJAX 调用中?
  • 是的,这是一个 AJAX 问题。您正在尝试在 httpGet(crawlingURL); 完成之前访问该数组。
  • 不,对 httpGet() 的调用会立即返回,而浏览器甚至不会启动 ajax 调用。它只是告诉浏览器在它有空闲 CPU 时间并且浏览器在 js 运行时没有空闲 CPU 时间时安排一个 HTTP 请求。只有在 js 完成运行并将执行传递给浏览器之后,浏览器才会注意到它必须发出 HTTP 请求。当请求在几秒钟后完成时,浏览器调用 ProcessRequest 回调。这就是回调的全部意义——一种让你告诉浏览器在一些异步事件之后要执行什么的机制。

标签: javascript function scope global-variables


【解决方案1】:

这就像你输入的那样工作 - 在这里摆弄http://jsfiddle.net/LmFqq/1/

输出

some code executing in A()
some code executing in B()
adding elements in C()
printing in A()
[0,1,2,3,4,5,6,7,8,9]

代码

var array = [];
var el = document.getElementById('output');
mainFun();

function log(msg) {
    el.innerHTML += msg + "<br />";
}

function mainFun()
{
     A();
}

function A()
{
    log("some code executing in A()");
    B();

    log("printing in A()");
    log(JSON.stringify(array));
}

function B()
{
    log("some code executing in B()");
    C();
}

function C()
{
    log("adding elements in C()");
     for (var i=0; i<10; i++)
     {
           array.push(i); //something on these lines
     }
}

【讨论】:

  • “你没有问题”不是答案。
猜你喜欢
  • 2023-03-22
  • 2014-01-17
  • 2012-03-06
  • 2018-12-23
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多