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

163
Visualizações
semi-space copy allocation failed, javascript heap out of memory

I was wondering why the below code returns a memory allocation error?

var countValidWords = function(sentence) {
    let words = [];
    for(let i = 0; i < sentence.length; ++i){
        let word = '';
        while(sentence[i] !== ' '){
            word += sentence[i];
            ++i;
        }
        if(word !== '')
            words.push(word);
    }
    console.log(words);
};

I'm simply trying to build an array of words from the inputted sentence (words can be separated by more than one space).

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

0

If the sentence doesn't end with a space, the while loop never ends, because it doesn't check if it has gone past the end of the string. As a result, you go into an infinite loop appending undefined to word, until you run out of memory.

Add a check that i is within the string length there.

var countValidWords = function(sentence) {
    let words = [];
    for(let i = 0; i < sentence.length; ++i){
        let word = '';
        while(i < sentence.length && sentence[i] !== ' '){
            word += sentence[i];
            ++i;
        }
        if(word !== '')
            words.push(word);
    }
    console.log(words);
};

about 4 years ago · Juan Pablo Isaza Relatório

0

The while clause needs to check for i getting out of bounds:

while(i < sentence.length && sentence[i] !== ' ')
about 4 years ago · Juan Pablo Isaza Relatório

0

How about this? It's not the most optimized version you might find but it works. You had an infinite loop on the while.

var countValidWords = function(sentence) {
    let words = [];
    let word = ''
    for(let i = 0; i < sentence.length; ++i){
        if(sentence[i] != '' && sentence[i] != ' '){
          word += sentence[i];
        }
        if(sentence[i] == ' ' || sentence[i + 1] === undefined){
          words.push(word);
          word = '';
        }
    }
    console.log(words);
};
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