What is the meaning of .slice (0) here?

I was studying jQuery source when I found this (line v1.5 2295):

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

My question is: why use slice(0) here?

+45
javascript jquery type-conversion slice
Feb 17 '11 at 1:14
source share
4 answers

sort() modifies the array it called on - and it's not very nice to bypass mutating things that other code can rely on.

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

+76
Feb 17 '11 at 1:17
source share
— -

arr.slice(0) creates a copy of the original array, taking a slice from the element with index 0 to the last element.

It is also used to convert objects like arrays to arrays. For example, the DOM NodeList (returned by several DOM methods such as getElementsByTagName ) is not an array, but it is an array-like object with a length field and indexed in JavaScript. To convert it to an array, it is often used:

 var anchorArray = [].slice.call(document.getElementsByTagName('a'), 0) 
+19
Feb 17 '11 at 1:16
source share

slice(0) allows you to return an array of the existing array you are referencing, in this case namespaces.

0
Feb 17 '11 at 1:18
source share

In addition to what @Anon said:

The slice() method selects elements starting with a given starting argument and ending with, but does not include, the specified ending argument.

Example 1:

 var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1, 3); 

The result of citrus fruits will be:

 Orange,Lemon 

Example 2:

 var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(-3, -1); 

The result of citrus fruits will be:

 Lemon,Apple 

Further information can be found here .

0
Mar 30 '17 at 19:22
source share



All Articles