As the browser reads an HTML document and forms a parse tree, JavaScript objects are
instantiated for all elements that are scriptable. Initially, the number of markup
elements that were scriptable in browsers was limited, but with a modern browser it
is possible to access any arbitrary HTML element.


但是,目前,作为脚本语言的新手,我主要关注可通过传统JavaScript对象模型(也称为DOM Level 0)访问的HTML元素,尤其是其相关元素,以使事情简单。

检测阵列
        尽管数组与对象并没有什么不同,但我们可以将它们视为对象,因此检测它们可能很重要。不幸的是,typeof不会有太大帮助。

    var arr = [];
    alert(typeof arr);            // "object"

    alert(arr instanceof Array);  // returns true

    alert(Array.isArray(arr));    // returns true


使用traditional JavaScript object model,我们可以使用<form>标签访问

window.document.forms


从基本意义上讲,它是一个看起来像数组的集合。
考虑一个非常基本的形式


    <form action="form1action.php" method="get">
        <input type="text" name="field1">

    </form>
    <br><br>

    <form action="form2action.php" method="get">
        <input type="text" name="field2">
        <br>
        <input type="text" name="field3">

    </form>

    <script type="text/javascript">

        console.log(typeof window.document.forms[1].elements[1]);            // object
        console.log(typeof window.document.forms[1].elements);               // object
        console.log(window.document.forms[1].elements instanceof Array);     // false
        console.log(window.document.forms instanceof Array);  // false

    </script>




我发现自己真的对意外行为感到困惑(这仅适用于我)

console.log(window.document.forms[1].elements instanceof Array);  // false
console.log(typeof window.document.forms instanceof Array);       // false


因为我有一种印象,JavaScript引擎会将某物[]作为Array的实例,因此在上述情况下,重点是elements and forms

最佳答案

并非所有具有索引属性([0], [1]等)的东西都是数组-它可以是任何类型的对象集合,这不是同一回事。它甚至可能只是具有0属性的对象,而根本不是集合。

在这种情况下,document.formsHTMLCollection-HTML元素的专用集合-并且window.document.forms[1].elementsHTMLFormControlsCollection,它继承自HTMLCollection



// all log true
console.log(window.document.forms instanceof HTMLCollection);
console.log(window.document.forms[1].elements instanceof HTMLFormControlsCollection);
console.log(window.document.forms[1].elements instanceof HTMLCollection);

// NOTE: typeof doesn't give the exact type of an object.
// This just logs "object", rather than "HTMLCollection", because it is an object, as opposed to e.g. a number
console.log(typeof window.document.forms);

var myObject = {0: 'foo', 1: 'bar'};
// log "foo bar"
console.log(myObject[0], myObject[1]);

<form></form>
<form></form>





Mozilla有关MDN的文档通常对于查看对象的实际类型非常有用,例如document.formsHTMLFormElement.elements

09-25 18:31
查看更多