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

326
Visualizações
How to chain two splice methods in Javascript?

In the following example, splice().splice() didn't work. What am I missing? How can I chain two splice methods in a single line? Thank you for any advice!

function test() {

  var data = [0,1,2,3,4,5];
  data.splice(0,2).splice(-1);  // Removed only the first two elements, but not the last element.
  console.log(data) // Returned [ 2, 3, 4, 5 ]

  var data = [0,1,2,3,4,5];
  data.splice(0,2); // Removed the first two elements.
  data.splice(-1);  // Removed the last element.
  console.log(data) // Returned [ 2, 3, 4 ]

}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

splice returns the removed elements, so chaining them in a single statement won't really work - you don't want to operate on the removed elements, you want to operate on the original array both times.

Usually, in this sort of situation, the right approach is to use slice instead, which is both easier to work with (just specify a start (inclusive) and end (exclusive) index) and is more functional (you get a new array instead of mutating an existing one - it's nice to avoid mutation when possible, makes code more understandable).

const data = [0,1,2,3,4,5];
console.log(data.slice(2,5));

about 4 years ago · Juan Pablo Isaza 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