【问题标题】:Array.prototype function not working for document.forms[0].elementsArray.prototype 函数不适用于 document.forms[0].elements
【发布时间】:2010-12-13 17:10:31
【问题描述】:

我已经为数组构建了一个原型函数,它不允许我将它与来自 d​​ocument.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] 数组,但不适用于我的元素数组?这是怎么回事,还是个数组?

【问题讨论】:

    标签: javascript arrays forms prototype


    【解决方案1】:

    这不是一个真正的数组,所以它不会继承Array.prototype

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

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

    编辑

    你可以通过调用把它变成一个真正的数组

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

    【讨论】:

    • 好的,谢谢。这清除了它。我只是可以将它变成一个数组,如下所示(这似乎可行,但我不确定它是否可取) var elems = document.forms[0].elements; //alert(elems.returnFirst().name); var newArr = 新数组(); var i = elems.length; while(i--){ newArr.push(elems[i]); } newArr.reverse(); alert(newArr.returnFirst().name);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    相关资源
    最近更新 更多