2013-10-28 24 views
-1

我有以下的javascript設置瓦爾使用循環

information0 = xmlDoc.getElementsByTagName("info")[0].textContent; 
information1 = xmlDoc.getElementsByTagName("info")[1].textContent; 
information2 = xmlDoc.getElementsByTagName("info")[2].textContent; 
information3 = xmlDoc.getElementsByTagName("info")[3].textContent; 
information4 = xmlDoc.getElementsByTagName("info")[4].textContent; 
information5 = xmlDoc.getElementsByTagName("info")[5].textContent; 
information6 = xmlDoc.getElementsByTagName("info")[6].textContent; 

我要創建每個索引編號的新變種。總共有600個。我如何使用for循環來做到這一點?

在此先感謝

+1

爲什麼不把它放在數組中 –

+1

你可以使用'Array' - 'information = [];信息[0] = xmlDoc ...; ...' –

+0

好的,所以我已經看到你所有的答案,但我需要給他們打電話,像這樣 'document.write(information0 +「
」); document.write(information1 +「
」); document.write(information2 +「
」); document.write(information3 +「
」); document.write(information4 +「
」); document.write(information5 +「
」); document.write(information6 +「
」);' – craig

回答

2

這裏最好的辦法是使用陣列,而不是一羣個體變量。

var information = []; 
var index; 
var info = xmlDoc.getElementsByTagName("info"); 
for (index = 0; index < info.length; ++index) { 
    information[index] = info[index].textContent; 
} 
+0

所以我想用這個,我可以回用: '文件撰寫(information0 +「
」);' 但我無法 – craig

+0

@craig:'document.write'在現代基本上沒有什麼地方web應用程序。如果您在初始頁面解析後使用它,會導致一個隱式的'document.open',它會清除頁面的內容。但是爲了稍後訪問這些信息,可以使用相同的表示法:'doSomethingWith(information [0]);''或'doSomethingWith(information [index]);'其中'index'是數組索引之一。 –

+0

好的,應該提醒(information0)工作嗎?我甚至無法完成這項工作 – craig

0

像這樣:

var information = [], 
    i, 
    elements = xmlDoc.getElementsByTagName("info"), 
    n = elements.length; 
for (i = 0; i < n; ++i) { 
    information[i] = elements[i].textContent; 
} 
1

嗯...使用數組?此外,不要重複撥打getElementsByTagName,它很貴!

var tags = xmlDoc.getElementsByTagName('info'), l = tags.length, i, information = []; 
for(i=0; i<l; i++) information[i] = tags[i].textContent; 

如果你在一個合理了最新的瀏覽器:

var information = [].map.call(xmlDoc.getElementsByTagName('info'),function(a) {return a.textContent;}); 
0

您需要使用數組。

var infoTags = xmlDoc.getElementsByTagName("info"), 
    i = 0, 
    len = infoTags.length, 
    values = []; //array literal syntax, you could also use new Array() 

for (; i < len; i++) { 
    values.push(infoTags[i].textContent); //push the textContent into the array 
} 

事情,你應該注意:

  • 我緩存,而不是多次執行查詢的getElementsByTagName結果。
  • 我緩存了length屬性infoTags。這避免了每次迭代訪問infoTags.length的多個屬性查找。在JavaScript中,屬性查找很昂貴。

要知道如何使用數組,請查看Array對象。 -

+0

如果你擔心費用問題,不要不必要地調用'push'。但是我質疑你的斷言:使用'len'而不是'infoTags.length'使600個元素的實際世界有所不同。 :-) –

+0

@ T.J.Crowder,也許不是,但這絕對是一種更好的做法,我相信這是值得一提的。 – plalx

+0

添加一個變量沒有真正的好處?不必要*。 :-) –