Two different outputs using + vs, concatenating methods

While working on this example on the MDN site explaining the filter method:

var arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, { }, { id: null }, { id: NaN }, { id: 'undefined' } ]; var invalidEntries = 0; function isNumber(obj) { return obj!== undefined && typeof(obj) === 'number' && !isNaN(obj); } function filterByID(item) { if (isNumber(item.id)) { return true; } invalidEntries++; return false; } var arrByID = arr.filter(filterByID); console.log('Filtered Array\n', arrByID); // Filtered Array // [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }] console.log('Number of Invalid Entries = ', invalidEntries); // Number of Invalid Entries = 4 

This is output in FireBug, as expected:

 Filtered array [Object { id=15}, Object { id=-1}, Object { id=0}, Object { id=3}, Object { id=12.2}] Number of Invalid Entries: 4 

But I initially mistakenly, but intentionally typed the first console.log (); as:

  console.log('Filtered array\n' + arrById); 

and got this FireBug output:

 Filtered array [object Object],[object Object],[object Object],[object Object],[object Object] Number of Invalid Entries: 4 

Why different outputs?

+6
source share
2 answers

Interaction with + calls the toString method on obj and therefore returns the string 'object' instead of returning the obj (name: value) property, which is returned by using , for concat on the console. log ().

+4
source

Take this simple object:

 var obj = { test: 5, another: 'hello' } 

If you do this console.log(obj) , then what you are requesting should write your object. He knows very well how to properly process the object, showing you all the properties and values.

However, if you do this console.log(obj.toString()) , you will ask javascript to convert the object to a string before asking firebug how to display it. Being a string, firebug will just display it as is. So the real question is: why does javascript convert an object to a string like [object Object] ... ?. You can see the explanation here.

In your question, using + , you force the object to convert to a string so that it can be combined with the 'Filtered array\n' bit.


If you want to do what you put in your question, but still have some useful results, you can try JSON.stringify() . For example: console.log('Filtered array\n' + JSON.stringify(arrById));

+1
source

Source: https://habr.com/ru/post/1015492/


All Articles