问题描述
这让我困惑,即使在Firefox 3.6中我也不能做 document.querySelectorAll(...)。map(...)
找不到答案,所以我想我会从这个博客交叉发帖的问题:
It bugs me that I can't just do document.querySelectorAll(...).map(...)
even in Firefox 3.6, and I still can't find an answer, so I thought I'd cross-post on SO the question from this blog:
有没有人知道你没有得到Array的技术原因?或者为什么StaticNodeList不会继承一个数组,你可以使用 map
, concat
等?
Does anyone know of a technical reason why you don't get an Array? Or why a StaticNodeList doesn't inherit from an Array in such a way that you could use map
, concat
, etc?
(BTW如果只是一个你想要的函数,你可以做 NodeList.prototype.map = Array.prototype.map; /code>...但是,为什么这个功能(故意?)被阻塞在第一位?)
(BTW if it's just one function you want, you can do something like NodeList.prototype.map = Array.prototype.map;
...but again, why is this functionality (intentionally?) blocked in the first place?)
推荐答案
p>我相信这是W3C的哲学决定。 W3C DOM [spec]的设计与JavaScript的设计非常正交,因为DOM是平台和语言中性的。
I believe it to be a philosophical decision of the W3C. The design of the W3C DOM [spec] is quite orthogonal to the design of JavaScript, as the DOM is meant to be platform and language neutral.
像 getElementsByFoo()
之类的决策会返回一个有序的 NodeList
或 querySelectorAll()
返回一个 StaticNodeList
是非常有意的,担心根据基于语言的实现调整返回的数据结构(例如 .map
可用于JavaScript和Ruby中的数组,但在列表中不是
Decisions like "getElementsByFoo()
returns an ordered NodeList
" or "querySelectorAll()
returns a StaticNodeList
" are very much intentional, so that implementations don't have to worry about aligning their returned data structure based on language-dependent implementations (like .map
being available on Arrays in JavaScript and Ruby, but not on Lists in C#).
W3C目标低:他们会说一个 NodeList
应该包含,因为他们相信每个实现至少可以支持 ,但他们不会明确说明 []
index运算符应该被重载以支持获取位置元素,因为他们不想阻止一些可能的小语言,它们想要实现 getElementsByFoo()
,但不能支持运算符重载。
The W3C aim low: they'll say a NodeList
should contain a readonly .length
property of type unsigned long because they believe every implementation can at least support that, but they won't say explicitly that the []
index operator should be overloaded to support getting positional elements, because they don't want to stymie some poor little language that comes along that wants to implement getElementsByFoo()
but cannot support operator overloading. It's a prevalent philosophy present throughout much of the spec.
John Resig拥有,:
John Resig has voiced a similar option as yours, to which he adds:
我有点同情。如果DOM是专门针对JavaScript特性编写的,那么使用起来会更加尴尬和更直观。同时,我也明白了W3C的设计决策。
I do somewhat empathize. If the DOM was written specifically with JavaScript features in mind it would be a lot less awkward and more intuitive to use. At the same time I do understand the W3C's design decisions.
这篇关于为什么document.querySelectorAll返回一个StaticNodeList而不是一个真正的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!