Why does document.querySelectorAll return a StaticNodeList rather than a real Array?

前端 未结 6 817
北恋
北恋 2020-11-30 01:11

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

6条回答
  •  孤独总比滥情好
    2020-11-30 01:20

    Just to add to what Crescent said,

    if it's just one function you want, you can do something like NodeList.prototype.map = Array.prototype.map

    Don't do this! It's not at all guaranteed to work.

    No JavaScript or DOM/BOM standard specifies that the NodeList constructor-function even exists as a global/window property, or that the NodeList returned by querySelectorAll will inherit from it, or that its prototype is writable, or that the function Array.prototype.map will actually work on a NodeList.

    A NodeList is allowed to be a ‘host object’ (and is one, in IE and some older browsers). The Array methods are defined as being allowed to operate on any JavaScript ‘native object’ that exposes numeric and length properties, but they're not required to work on host objects (and in IE, they don't).

    It's annoying that you don't get all the array methods on DOM lists (all of them, not just StaticNodeList), but there's no reliable way round it. You'll have to convert every DOM list you get back to an Array manually:

    Array.fromList= function(list) {
        var array= new Array(list.length);
        for (var i= 0, n= list.length; i

提交回复
热议问题