【发布时间】:2015-03-13 19:41:07
【问题描述】:
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 对象模型访问的 HTML 元素 /em>(也称为 DOM 级别 0),尤其是 和 其相关元素,以保持简单。
检测数组
虽然 数组 与 对象 并没有什么不同,但我们可能会这样对待它们,并且检测它们可能很重要。不幸的是,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 引擎会将 something[] 视为 instanceof >数组,在上面的例子中关注elements and forms。
【问题讨论】:
-
我发现你的问题有点令人困惑,但你似乎是说如果方括号
[]可以与对象一起使用,它必须是一个数组?事实并非如此。方括号语法可用于访问任何对象的属性。在您的示例中,forms是一个类似数组的对象,但实际上不是一个数组。 -
@nnnnnnn:不,我很清楚 document["write"] 不会让 document 表现得像一个数组。我说,我的案例是关注元素和形式。
-
正如我所说,
forms是一个类似数组的对象,而不是数组。 -
@nnnnnn:感谢您伸出援助之手。再次感谢您,真的!。
标签: javascript arrays forms dom