Array representation
I wonder what is the difference between array view between []
and (3) [Object,Object,Object]
?
I have an array of objects like:
var array = [{id: 1, text: 'a'}, {id: 2, text: 'b'}, {id: 3, text: 'c'}];
when i tried console.log(array)
on some line in my codes, once printed like []
and sometimes like (3) [Object,Object,Object]
. []
is not empty, however, when I expanded it in the browser console, both contain the same values (3 objects).
in my case when i use var array
as data for mine select2
like this:
$('#elems').select2({
data: array
});
if when i console.log(array)
and it is displayed as (3) [Object, Object, Object]
, select2
gets data and option will be a,b,c
. but when it shows that []
select2
it could not read the objects, that way, the parameter will be empty.
I wonder if it select2
reads []
as empty, although the browser console []
is extensible and contains a value. eg:
can someone explain about this?
source to share
It is the matter of time. console.log runs before items are added. Follow this snippet for an example. You should have hit the timing just right. Most likely a race condition.
var array = [{id: 1, text: 'a'}, {id: 2, text: 'b'}, {id: 3, text: 'c'}];
console.log(array);
var array = [];
setTimeout(function(){
array.push({id: 1, text: 'a'}, {id: 2, text: 'b'}, {id: 3, text: 'c'});
}, 1000);
console.log(array);
source to share
The one-line display in the JavaScript console is generated the moment you call console.log()
.
When you click the arrow icon later, a multi-line display will be created when you click the arrow.
This is why you see two different things: you changed the array some time after the initial call console.log()
, but before you clicked the arrow.
If you want to see that the contents of a complete array existed in it at the time of the call console.log()
, a good way to do this is to use JSON.stringify()
:
console.log( JSON.stringify( array, null, 4 ) );
If you don't know why this happened, the likely bet is that you have an asynchronous operation that modifies the array after you've made the original call console.log()
. For example, a common mistake is to make an ajax call to populate a global variable, and then you try to immediately use that variable in your code after the ajax call returns - but that is before the data is ready and the ajax callback is called.
In this case, you shouldn't use a global variable at all. Instead, you should handle the data returned from the server in the ajax callback itself, or in a function called from that callback. Don't try to store it in a global variable, and don't assume your other code knows when the data is ready. Access the data only in the callback.
source to share