即使在Firefox3.6中我也不能只做document.querySelectorAll(...).map(...)
,这让我很困扰,我仍然找不到答案,所以我想我应该交叉发布这个博客上的问题:
http://blowery.org/2008/08/29/yay-for-queryselectorall-boo-for-staticnodelist/
有没有人知道为什么你没有得到一个数组的技术原因?或者为什么StaticNodeList不能以可以使用map
、concat
等的方式从数组继承?
(顺便说一句,如果它只是你想要的一个功能,你可以再次做类似NodeList.prototype.map = Array.prototype.map;
...but的事情,为什么这个功能是故意的?)一开始就被屏蔽了?)
发布于 2016-07-04 00:16:05
您可以使用ES2015 (ES6) spread operator
[...document.querySelectorAll('div')]
将StaticNodeList转换为项的数组。
这里有一个关于如何使用它的例子。
[...document.querySelectorAll('div')].map(x => console.log(x.innerHTML))
<div>Text 1</div>
<div>Text 2</div>
发布于 2010-04-08 22:14:32
我不知道为什么它返回一个节点列表而不是数组,可能是因为像getElementsByTagName一样,当您更新DOM时,它会更新结果。无论如何,将结果转换为简单数组的一个非常简单的方法是:
Array.prototype.slice.call(document.querySelectorAll(...));
然后你可以这样做:
Array.prototype.slice.call(document.querySelectorAll(...)).map(...);
发布于 2021-05-08 04:25:07
Array.from(document.querySelectorAll(...)).map(...)
通过https://caniuse.com/mdn-javascript_builtins_array_from在IE11上不可用
https://stackoverflow.com/questions/2600343
复制相似问题