Javascript Array.prototype函数不适用于document.forms[0]。元素

Javascript Array.prototype函数不适用于document.forms[0]。元素,javascript,arrays,forms,prototype,Javascript,Arrays,Forms,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: <inpu

我已经为数组构建了一个原型函数,它不允许我将其用于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>

名字:
姓氏:
返回表单中每个元素的值:

Array.prototype.returnFirst=函数(){ 返回此[0]; } 警报([1,2,3].returnFirst())//为什么这样做有效? 警报(document.forms[0].elements.returnFirst().id)//但是这个没有?

您将看到returnFirst()原型函数适用于我的[1,2,3]数组,但不适用于我的元素数组?这是为什么,它仍然是一个数组?

这不是一个真正的数组,所以它不会继承
数组。原型

它实际上是一个
HTMLCollection
,您可以通过调用
toString()
来发现这一点

如果愿意,可以修改
HTMLCollection.prototype
,但是

编辑

您可以通过调用

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

好的,谢谢。这就把事情弄清楚了。我只是我可以将它转换成一个数组,如下所示(这似乎可行,但我不确定是否可取)var elems=document.forms[0].elements//警报(elems.returnFirst().name);var newArr=新数组();var i=元素长度;而(i--){newArr.push(elems[i]);}newArr.reverse();警报(newArr.returnFirst().name);