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

241
Visualizações
Array map calls the constructor of a class that extends Array instead of calling Array constructor

Calling map() on an instance text of ConsoleText class that extends Array results in a ConsoleText(text.length) call (constructor input: 2 in the last line).
How to fix it so that text.map() calls Array constructor instead? Or it is a feature of inheritance?

EDIT: found an answer here

'use strict'

let initializingText = true;

class ConsoleText extends Array {
  constructor(strings) {
    console.log('constructor input:', strings);
    if (initializingText) {
      super(...strings);
    } else {
      super('item1', 'item2', 'item3', 'item4', 'item5');
    }
  }
}

let text = new ConsoleText(['a', 'b']);   // constructor input: (2) ['a', 'b']

console.log('text:', text);   // text: ConsoleText(2) ['a', 'b']

initializingText = false;   // switch to escape error destructuring a number

console.log(text.map(() => 'q'));   // constructor input: 2
                                    // ConsoleText(5) ['q', 'q', 'item3', 'item4', 'item5']
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Array.constructor accepts two different types of arguments:

  • new Array(element0, element1, /* … ,*/ elementN) - list of elements to create new array
  • new Array(arrayLength) - array length, it will create an empty array then.

So when you call Array.map, it will create a new array with the same instance class, pass array length into constructor and then will use Array.push to update that array. That is the reason why map logs array length in your case.

Furthermore, I do not recommend extending default data structure cause it can be really confusing. Maybe in your case you can just create a simple function, that returns generated array?

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