Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of .slice(0) here?

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

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

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

like image 689
mVChr Avatar asked Feb 17 '11 01:02

mVChr


People also ask

What does. slice 0 1 do?

Add details and clarify the problem by editing this post. Closed 3 years ago. I know that in string with name example example. slice(0, -1) it removes last character from it.

What does slice 0 do?

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.


2 Answers

sort() modifies the array it's called on - and it isn't very nice to go around mutating stuff that other code might rely on.

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.

like image 62
Anon. Avatar answered Sep 16 '22 18:09

Anon.


arr.slice(0) makes a copy of the original array by taking a slice from the element at index 0 to the last element.

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) 
like image 44
ide Avatar answered Sep 16 '22 18:09

ide