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

174
Visualizações
Extend JavaScript Array prototype with method to iterate entries in reverse?

Putting aside concerns about modifying JavaScript's Array.prototype for now, how would I go about writing a custom method on the Array prototype that returns an iterator in reverse? Specifically, I'd like to provide an entriesReverse() method that does exactly what Array.prototype.entries() does except in reverse order. I've got as far as a bespoke function:

const entriesReverse = (array) => ({
    [Symbol.iterator]() {
        let index = array.length;
        return {
            next: () => ({
                value: [--index, array[index]],
                done: index < 0
            })
        }
    }
})

but I'll be darned if I can figure out how to implement this as a method on the existing Array prototype. The problem seems to be trying to refer to 'this' inside the Symbol.iterator block - it doesn't refer to the array itself but to the iterator. Any thoughts?

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

0

It'll be easier to use a generator function. Call the original .entries() and turn it into an array of the entries, then iterate backwards over that array and yield each item.

Array.prototype.entriesReverse = function*() {
  const entries = [...this.entries()];
  for (let i = entries.length - 1; i >= 0; i--) {
    yield entries[i];
  }
};

for (const entry of ['a', 'b', 'c'].entriesReverse()) {
  console.log(entry);
}

Another option:

Array.prototype.entriesReverse = function*() {
  yield* [...this.entries()].reverse();
};

for (const entry of ['a', 'b', 'c'].entriesReverse()) {
  console.log(entry);
}

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