What is the use of Array.prototype.slice.call (array, 0)?

I was just looking at the Sizzle source code, and I came across this line of code:

array = Array.prototype.slice.call( array, 0 ); 

I looked at what this function is, but I came to the conclusion that it simply returns all the elements of the array, starting at index 0, and puts the integer in the array, i.e. he does nothing at all.

What is the use of this line of code? What am I missing?

Edit: This is line 863 from https://github.com/jquery/sizzle/blob/master/sizzle.js#L863 .

+46
javascript arrays sizzle
Feb 28 2018-11-18T00:
source share
3 answers

The DOM usually returns a NodeList for most operations, such as getElementsByTagName .

Although NodeList almost like an array, it is not. It has a length property, similar to an array, and an item(index) method for accessing an object at the specified index (also available using the [index] notation), but the one where the similarity ends.

So, to use the wonderful array methods without rewriting them all for NodeList , the above line is useful.

Another use of conversion to array is to make the list static. NodeLists usually live, which means that when a document changes, the NodeList object is automatically updated. This can cause problems if the jQuery object returned to you is constantly changing right under your nose. Try running the snippet to test the functionality of NodeLists.

 var p = document.getElementsByTagName('p'); console.log(p.length); // 2 document.body.appendChild(document.createElement('p')); // length of p changes as document was modified console.log(p.length); // 3 
+75
Feb 28 '11 at 17:13
source share

What happens here is that Sizzle creates an actual array from an object similar to an array. An array-like object does not have to have a slice () method, so the prototype method must be called directly. makeArray() returns a copy of this massive-like object, which is the actual array, and can be used as such, where.

See here for more information on objects like an array.

+10
Feb 28 2018-11-28T00:
source share

As BoltClock says, it makes a (shallow) copy of the array. It can also be used to copy something that is almost an array, such as an inline arguments that has length and elements but does not contain an array in the prototype chain (and therefore not a slice method).

+6
Feb 28 2018-11-18T00:
source share



All Articles