This is discussed in detail in the StackOverflow link. Stackoverflow.com/questions/5…

A user who is learning the jQuery source code is confused by the following line of code:

namespace = new RegExp("(^ | \ \.) " +
  jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\ \. (? :. * \ \.) ?") + "(\ \ | $)");
Copy the code

Applying sort to an array alters the original positions of elements in the data that called sort. So to ensure no side effect on the original array called by the sort method, we use slice(0) to make a deep copy of the original array:

slice() always returns a new array – the array returned by slice(0) is identical to the input, which basically means it’s a cheap way to duplicate an array.

Another useful way to use slice is to convert an array-like object into a real array object. So-called class array object, an example is the API document. The getElementsByTagName the result returned NodeList type: although not a real array, but the length attribute, support with JavaScript visit each element according to the index. Using var anchorArray = []. Slice. The call (the document. The getElementsByTagName (‘ a ‘), 0) solution to such a big move, borrowed from the [] the native arrays provide slice method, You can easily convert NodeList into a real JavaScript array.

It’s also used to convert array-like objects into arrays. For example, a DOM NodeList (returned by several DOM methods like getElementsByTagName) is not an array, but it is an array-like object with a length field and is indexable in JavaScript. To convert it to an array, one often uses:

var anchorArray = [].slice.call(document.getElementsByTagName('a'), 0)
Copy the code

For more of Jerry’s original articles, please follow the public account “Wang Zixi “: