Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
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?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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 was 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 used:

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

Now, ES2015's spread syntax is used to convert iterable objects, including NodeList and HTMLCollection, to arrays:

const anchorArray = [...document.getElementsByTagName('a')]
over 4 years ago · Santiago Trujillo Relatório

0

slice(0) creates a new array identical to the original array. Many times you want to preserve your original array and create a new one.

If you use slice(1), it will create a different array starting from index position 1.

Similar things hold for strings as well.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda