In the evening, I found the usage of [].splice. Call () in an article written by Zhang Xinxu. I was very interested in it, because I just wrote a blog about call method titled “A Reading of CALL and Apply in JS” (hereinafter referred to as “Call”) yesterday.
Basis:
- The slice() method returns selected elements from an existing array with the syntax:
array.slice(start, end)
[start, end]; [start, end]; - Slice () arguments can be omitted, starting at 0 and ending at the last bit, which returns all;
- Call and apply are used to call functions in a specific scope, for example:
Programmer. Programming. Call (delivery man)
This is to call the programmer’s programming method in the takeout man scope, namely takeout man programming.
Approach:
[].slice.call(eleRadios) Is written so that eleRadios can call the native method of an array, Slice (), to convert to an array format. Isn’t eleRadios an array? Have to go all the way around? Some of his code is posted below (the full version is here) :
// Delete some extraneous code <inputtype="radio" value="default" checked>
<input type="radio" value="red">
<input type="radio" value="green">
var eleRadios = document.querySelectorAll('input[type="radio"]');
[].slice.call(eleRadios).forEach(function (radio) {
radio.addEventListener('click'.function() {// omitted}); });Copy the code
All through the document. QuerySelectorAll access page type is equal to the input node set eleRadios “radio”, then to []. Slice. Call forEach traversal (eleRadios), Add a click event to each of the child elements. Why not call the forEach method directly — like eleradios.foreach (…) ? So eleRadios really isn’t an array? I tested it in the debug tool console on the page and found it was correct:
I print out that eleRadios is of type NodeList, and to verify its relationship to an array again, I use instanceof. The result is clear: it is not an array.
If you test on newer browsers like Chrome, you’ll find that the NodeList type can call forEach(), but this feature is not stable. On older browsers, NodeList doesn’t support forEach(), so, Zhang Xinxu wrote this should be to solve the compatibility problem. In real development, it would be safer to use [].slice.call() to convert it to an array type and then call some of the array’s methods.
Principle:
It should now be clear that to iterate over the NodeList eleRadios, we use the call method: call the slice method of the array in the eleRadios scope to convert to the array type, and then call the forEach method to iterate.
Since [] is an instance of Array, it can also be written as [].slice.call().
Christmas supplement on December 25, 2019
Class array to array ES6
const arr = Array.from(eleRadios)
const arr = [...eleRadios]
Copy the code