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

105
Visualizações
Why does console.log display array different than alert?

I wrote a function that filters objects in a specific manner (grouped by key but only consecutive ones, it works fine).

groupBySequentialValues(array, key) {
    let groupName = null;
    let groupIndex = 0;
    let result = []; // keep this in mind!

    array.forEach((el, index) => {
        if (groupName !== array[index][key]) {
            groupName = array[index][key]
            groupIndex++;
            result[groupIndex + '_' + groupName] = []
        }
        result[groupIndex + '_' + groupName].push(el);
    })

    alert(result);
    console.log(result);
}

At first the alert shows an empty array, but after the alert is closed, the console log will show the correctly assembled array. (This also happends without the alert of course, this just shows the difference the best)
But I cannot use this array in alerts or in the template (I use it in VueJS to render a list, but its empty like I said).

Somehow dev tools seems to see its contents but alert/the dom doesnt.
After declaring the result array as an object ({} instead of []) it worked.

Why does dev tools/console log behave this way? Its a debug tool, but when it behaves like this I cannot rely on it as a debugging tool..

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

0

When constructing an object and printing that object to the console, console.log() will output the object's own properties and their values. If you console.log() the object using the object's .toString() method you will receive [object Object] in the console. This is the exact result you see in the alert of the object:

const obj = {};
obj['test'] = 'this is a test';
console.log(obj);
console.log(obj.toString());
alert(obj);

If you create an array and console.log() its internal toString() method prints the elements of the array comma separated with [] surrounding them. When alert()ing an array, the .toString() method is used to print only the array values:

let arr = [1,2,3];
console.log(arr);
alert(arr);

Finally, your code adds properties to an Array Object rather than adding elements to the array. When this occurs, console.log() prints this Object exactly like the first example, but because this is an Array Object, it places [] around the properties and their values rather than {}. Since the array is empty (no elements), it prints [] literally.

The code below demonstrates the structure of the Array Object your code creates, shows the number of array elements is zero, shows the Array Object's property names, shows the value associated with that property and finally shows the object in the console.

If you alert the result as explained in the previous example, the dialog will be empty because there are no elements in the array.

let groupName = 'test';
let groupIndex = 0;
let el = 'this is a test';
let result = [];

result[groupIndex + '_' + groupName] = []
result[groupIndex + '_' + groupName].push(el);

console.log('Number of elements in result array: ', result.length);
console.log('result Object Property Names: ', Object.getOwnPropertyNames(result));
console.log('result Object Property Value: ', result[Object.getOwnPropertyNames(result)[1]]);

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

A JavaScript Array is an array of course, but it is also an Object.

And more, it accept index as string without problem:

const a = [1, 2, 3]
console.log(a[0])
console.log(a['0'])

Those console.log will output the first value of the array = 1.

So the Array is wide tollerant and that is why it should be used carefully to avoid suprises in a form of very hard to debug bugs.

In your case you should use an Object or a Map.

UPDATED

Also consider that the window.alert is very different from console.log.

The window.alert attempt to print a string format of the input, that should be passed as a string, but if it is not, then it is forced.

That mean that this:

const x = {}
alert(x)

Will print [object Object]. While if you use:

console.log(x)

You will see:

{}

And you will be able to browse the object methods and attributes, even the object is empty.

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