2010-12-13 60 views
0

我已經爲數組構建了一個原型函數,並且它不允許將它與document.forms [0] .elements中的數組一起使用。這裏是一個簡化的腳本,顯示這個問題Array.prototype函數不適用於document.forms [0] .elements

<html> 
<body> 

<form id="frm1" action="form_action.asp"> 
    First name: <input type="text" name="fname" value="Donald" /><br /> 
    Last name: <input type="text" name="lname" value="Duck" /><br /> 
    <input type="submit" value="Submit" /> 
</form> 


<p>Return the value of each element in the form:</p> 
<script type="text/javascript"> 
Array.prototype.returnFirst = function(){ 
    return this[0]; 
} 
alert([1,2,3].returnFirst()); //Why does this work? 
alert(document.forms[0].elements.returnFirst().id); //but this one doesn't? 
</script> 

</body> 
</html> 

您將與此看到returnFirst()函數原型的作品對我的[1,2,3]數組,但不是我的元素的數組?這是爲什麼,它仍然是一個數組?

回答

1

這不是一個真正的數組,因此它不會繼承Array.prototype

它實際上是一個HTMLCollection,你可以通過調用toString()來發現它。

如果你願意,你可以修改HTMLCollection.prototype,但是modifying DOM prototypes is discouraged

編輯

你可以通過調用

var arr = Array.prototype.slice.call(document.forms[0].elements); 
+0

好,感謝把它變成一個真正的數組。這清除了它。我只是我可以把它變成一個數組如下(這似乎工作,但我不確定是否是明智的)var elems = document.forms [0] .elements; //alert(elems.returnFirst().name); var newArr = new Array(); var i = elems.length;同時(i - ){newArr.push(elems [i]); } newArr.reverse(); alert(newArr.returnFirst()。name); – 2010-12-13 17:17:51

+0

@Emdiesse:看我的編輯。 – SLaks 2010-12-13 17:27:19

相關問題