2015-06-09 41 views
-3

我正在使用下面的函數來加載xml,然後返回帶有值的數組。 但是,當我在另一個函數中調用它時,它會給出錯誤「arrXML未定義」。如何返回數組

function readXML() { 
    // create an array object 
    var arrXML = new Array(); 

    //create XML DOM object 
    var docXML = Sys.OleObject("Msxml2.DOMDocument.6.0"); 

    // load xml 
    docXML.load("C:\\Users\\ankit\\Desktop\\read.xml"); 

    // search nodes with 'config' tag 
    var Nodes = docXML.selectNodes("//config"); 
    for (i = 0; i < Nodes.length; i++){ 
     var ChildNodes = Nodes.item(i); 
     arrXML[i] = Nodes(i).childNodes(0).text +":"+Nodes(i).childNodes(1).text; 
    } 
    // return array of XML elements 
    return arrXML; 
} 

function getvalues() { 
    log.message(arrXML[1]); // this line gives error 
} 
+0

您不檢查以確保文檔正確加載或任何變量以其中的數據結束。 – BSMP

+0

文檔正在成功加載。如果像log.message(readXML()[1])那樣打印,它將在另一個函數中打印這些值。但我不想這樣稱呼它。它應該被直接調用 – vinu

+2

'arrXML'是'readXML'的本地語言,因爲你在該語句塊中用'var'聲明瞭它。 'getValues'不知道它是否存在(因爲它不再存在) – Gary

回答

0

arrXML是本地功能readXML,因爲你與該塊內的var關鍵字聲明它。 getValues不知道它存在(因爲它不再)。

你的選項,使全局變量(你應該小心)

vinu = {}; // vinu is global namespace containing the array 
function readXML() { 
    vinu.arrXML = []; 
    // ... 
    return vinu.arrXML; // This might not even be necessary in this case 
} 

function getvalues() { 
    log.message(vinu.arrXML[1]); 
} 

...或者當你調用它的變量傳遞給函數。

function getvalues(arg) { 
    log.message(arg[arrXML[1]]); 
    return arg; // This function can't change the original variable, so use the return if need-be 
} 

// Somewhere that has access to the actual "arrXML" 
getvalues(arrXML); 

...或使用閉包。