While working on this example at 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 gets 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, errantly but intentionally typed the first console.log(); statement 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 the different outputs?
Concatting with the +
calls toString
method on the obj and so returns the string 'object' instead of returning the obj property (name: value) as is returned using the ,
to concat by the console.log() output.
Take this simple object:
var obj = {
test: 5,
another: 'hello'
}
If you do this console.log(obj)
, what you are asking firebug to do is log your object. It knows how to deal with an object in a nice way, showing you all the properties and values.
However if you do this console.log(obj.toString())
, you are asking javascript to convert your object to a string before asking firebug how to display it. Being a string, firebug will simply display it as is. So the real question is, why does javascript convert an object to a string like [object Object] ...
?. You can see an explanation here
In your question, by using the +
, you are forcing the object to be converted to a string so that it can be concatenated with the 'Filtered array\n'
bit.
If you want to do what you have put in your question, but still have somewhat useful outputs, you can try JSON.stringify()
. For example: console.log('Filtered array\n' + JSON.stringify(arrById));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With