Javascript TypeError ____ is not a function

后端 未结 4 1618
野性不改
野性不改 2021-01-27 02:46

I am currently using the Chrome console to do some debugging for a Greasemonkey script.

From the console I run var opp = document.querySelectorAll(\'a[class=\"F-re

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-27 03:03

    First,

    • splice is a method of Arrays, inherited through Array.prototype, although it is intentionally generic so can be called on other Arraylike objects
    • querySelectorAll returns a non-live NodeList, this is not an Array and does not share any inheritance with Array, meaning you can't simply access Array methods through it
    • A function can be invoked with a custom this via call or apply
    • splice needs to be able to assign on it's this, which will fail for a NodeList as you will get the following TypeError: Cannot set property length of # which has only a getter
    • Other intentionally generic Array methods which only read from this will work on a NodeList, e.g. slice, map, indexOf, forEach, filter, some, every, etc..

    Now we are in a position to do something,

    1. Convert the NodeList to an Array and store this reference, i.e. with Array.prototype.slice
    2. Perform your splice on this object instead

    So,

    var opp = document.querySelectorAll('a[class="F-reset"]'); // NodeList
    oop = Array.prototype.slice.call(oop); // Array
    // ...
    oop.splice(0, 1);
    

提交回复
热议问题