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

186
Visualizações
JS: No contents in array from parent class

I am using two classes in javascript.

class Challenge and class Modules, that extends Challenge.

in Challenge i have this constructor:

constructor() {
    this.handles = [];
}

and this method:

bla() {

    let elmnts = document.querySelectorAll("p"); // 5x
    
        for(let i=0; i < elmnts.length; i++) {
        
            let elmnt = elmnts[i];
            this.handles[elmnt['id']] = elmnt; // saves the handles to each element in separate array for later use
        
        }

}

in the child Class i am trying to use this "this.handles" array, but it is always empty.

It is not "undefined" but it is an empty array as i defined it in the constructor. its like the entries have never been set... but they are (as console.log() shows, when i insert it directly after the for()-loop)

console.log(this.handles); // --> []

Why does this happen?

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

0

this.handles is an array. So when you are doing this.handles[elmnt['id']], elmnt['id'] returns a string, whereas an array expects (positive) integer for index. So the elements are not set in the array.

Maybe you meant this.handles to be an object?

class Ex1 {
  constructor() {
    this.handles = {};
  }

  bla() {

    let elmnts = document.querySelectorAll("p"); // 5x

    for (let i = 0; i < elmnts.length; i++) {

      let elmnt = elmnts[i];
      this.handles[elmnt['id']] = elmnt; // saves the handles to each element in separate array for later use
    }
    
  }
}

class Ex2 extends Ex1 {
  constructor(){
    super();
  }
  
  m1(){
    console.log(this.handles);
  }
}

let p1 = new Ex2();
p1.m1();
p1.bla();
p1.m1();
<p id="one">1</p>
<p id="two">2</p>
<p id="three">3</p>
<p id="four">4</p>
<p id="five">5</p>

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to understand the following things:

In Javascript...

  • ... Arrays are always index-based (0 pointing to the first array element).
  • ... you append elements to an array using arr.push(el).
  • ... Arrays are also objects, so adding arbitrary properties also works (which is what you are doing by using the p element id as a key and assigning it the element reference). See this example:

enter image description here

If you need an array (which preserves order and can easily be iterated later on), just spread the NodeList you got from querySelectorAll('p') into the array using the ES6 spread syntax ...:

this.handles = [...document.querySelectorAll("p")];
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