【问题标题】:A pretty strange issue caused by HTML DOM's "querySelectorAll" method or "getElementsByTagName" method由 HTML DOM 的“querySelectorAll”方法或“getElementsByTagName”方法引起的一个非常奇怪的问题
【发布时间】:2012-07-28 07:13:38
【问题描述】:

查看代码:

<!DOCTYPE html>
<meta charset="utf-8">
<title>An HTML5 Document</title>
<p>
<p>
<script>
    var a = [1, 2],
        b = [3, 4],
        c = a.concat(b),
        d, e, f, g;

    console.log(c); // No problem

    d = [document.querySelectorAll('p')[0], document.querySelectorAll('p')[1]];
    e = a.concat(d);
    console.log(e); // No problem

    f = document.querySelectorAll('p'); // f = document.getElementsByTagName('p');
    g = a.concat(f);
    console.log(g); // Pretty strange...
</script>

jsFiddle:http://jsfiddle.net/V7gmE

我的问题是:

c.length4。没有问题。 e.length4。没问题。

如果我使用f = document.querySelectorAll('p');f = document.getElementsByTagName('p');,为什么g.length 是'3'?

谢谢。

【问题讨论】:

  • 这不是真正的生产代码,对吧? d = [document.querySelectorAll('p')[0], document.querySelectorAll('p')[1]]; 无缘无故将您的处理量翻倍。
  • 这些代码是专门为这个问题写的。

标签: getelementsbytagname dom selectors-api


【解决方案1】:

没问题,你的第三个数组只是[1, 2, NodeList].querySelectorAll 返回一个NodeList,在这种情况下它包含两个元素。在第二个示例中,您专门从 NodeList 中获取第一个和第二个元素并将它们放入一个数组中。虽然 NodeList 可能看起来像数组,但它们不是,并且当您在其上使用 Array.concat 方法时,不会挑选出单个元素。

来自MDN

NodeList 的使用与数组非常相似,在它们上使用 Array.prototype 方法会很诱人。然而,这是不可能的。

这是另一个可能有助于理解这一点的示例:http://jsfiddle.net/radu/j5gvy/1/

var a = [1, 2],
    obj = { 0 : '', 1 : ''},
    b = [obj[0], obj[1]];

c = a.concat(obj);

console.log(c.length); // 3

d = a.concat(b);

console.log(d.length); // 4

仅仅因为我定义了一个可以像数组一样访问的对象并不能使它成为数组。

【讨论】:

  • querySelectorAll 返回一个数组,就像[document.querySelectorAll('p')[0], document.querySelectorAll('p')[1]] 所做的一样。但我最终得到不同的结果......
  • 它不返回一个数组 - 它返回一个NodeList。当您执行document.querySelectorAll('p')[0] 时,您将从NodeList 中取出第一个元素。碰巧它们的处理方式相似,但您无法有效地使用Array.concatArray.prototype 中的其他方法,除非您按照您所做的操作并首先挑选出单个结果。
  • 添加了一个可能有助于说服您的示例。
  • 谢谢。拉杜。在看到您的回复和您提供的 MDN 资源后,我认为querySelectorAll 返回的是一个对象,而不是一个数组。我觉得网络最糟糕的部分可能是 HTML DOM。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-26
  • 1970-01-01
  • 2021-08-26
  • 2011-07-12
  • 1970-01-01
相关资源
最近更新 更多