我正在开发一个类似于以下内容的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 />";
}
}
}
}
我无法打印我的排队数组中的值! (您可能已经理解,这是某种网络爬虫的初步代码。我需要获取推入排队数组的所有URL列表。)
答案 0 :(得分:0)
这就像你输入它一样 - 在这里摆弄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
}
}