2012-02-03 18 views
2

我將HTML集合對象用作數組並將其添加到其中。下面的代碼,Javascript HTMLCollection對象在firefox10中無法正常工作

var claimantEmailValues = document.getElementsByName("claimantEmails"); 
var defendantEmailValues = document.getElementsByName("defendantEmails"); 


var k = defendantEmailValues.length; 
for(var i=0; i<claimantEmailValues.length;i++){ 
     defendantEmailValues[k++] = claimantEmailValues[i]; 
} 

在末端,的defendantEmailValues長度應該是4,因爲我有每兩個HTML輸入元素爲claimantEmailsdefendantEmails。相反,長度是2,沒有錯誤。它在除Firefox以外的所有firefox版本中運行良好。你能解釋一下爲什麼嗎?

回答

3

JavaScript數組是具有魔術的對象當您將數字屬性設置爲等於或高於當前長度時,length屬性會增加。 HTMLCollection對象具有長度屬性,但它不是魔術,並且在設置數字屬性時不應該增加。當你給它們添加一個元素時,你實際上只是將一個命名屬性添加到一個對象中,使用一個數字作爲屬性名稱。

你最好轉換集合到數組首先使用Array.prototype.slice

var slice = Array.prototype.slice, 
    claimantEmailValues = slice.call(document.getElementsByName("claimantEmails")), 
    defendantEmailValues = slice.call(document.getElementsByName("defendantEmails")); 

var k = defendantEmailValues.length; 
for(var i=0; i<claimantEmailValues.length;i++){ 
     defendantEmailValues[k++] = claimantEmailValues[i]; 
} 

這可能是因爲以前的Firefox版本的行爲是錯誤的,允許項目被添加到HTMLCollection實例和錯誤纔剛剛在Firefox 10中修復。

+0

謝謝安迪。但是,我能夠檢索長度屬性,我的問題是執行「defendantEmailValues [k ++] = claimantEmailValues [i]''語句後,長度沒有增加。 – 2012-02-03 10:33:04

+0

@SelvakumarP:是的,我的回答說這個屬性不像JavaScript數組那樣「魔術」。這就是爲什麼它不會增加。讓我稍微澄清第一段。 – 2012-02-03 10:36:39

+0

謝謝安迪!得到它了 :-) – 2012-02-03 10:43:18