I have a javascript function that returns an array of objects. The array looks like this: array
I want to use $.each() to iterate through the array and do some things with the objects' properties. However, $.each() doesn't fire at all. For example, this:
myArray = myFunc();
$.each(myArray, function(index, object){
console.log('testing testing 1 2 3');
}
doesn't do anything at all. No console.logs.
However, if I do this:
myArray = myFunc();
console.dir(myArray);
$.each(, function(index, object){
console.log('testing testing 1 2 3');
}
in Firefox it produces the output shown above - I can see all the objects in the array just fine.
However, console.log() shows simply
Array [ ]
How is it possible for the array to simultaneously be empty, AND have contents that console.dir() can show?
FWIW, this ugly mess is what the function (generated in part by PHP) ends up looking like:
instance = false;
function checkMessages() {
var messageArray = [];
$('#newMessages').html('0');
if (!instance) {
instance = true;
myMessages = 0;
myRead = 0;
delete data;
$.ajax({
type : 'POST',
url : 'Chat/process.php',
data : {
'function' : 'getState',
'filename' : 'data/chat_2_1.txt',
},
dataType: 'json',
success: function(data){
myMessages = data.state;
messageArray[2] = {
'filename' : 'chat_2_1.txt',
'divname' : 'msg_2',
'length' : data.state,
};
},
}).done(function(){
delete data;
$.ajax({
type : 'POST',
url : 'Chat/process.php',
data : {
'function' : 'getReadByMe',
'filename' : 'log/chat_2_1_2.txt',
},
dataType: 'json',
success: function(data){
messageArray[2].read = data.read;
},
});
});
myMessages = 0;
myRead = 0;
delete data;
$.ajax({
type : 'POST',
url : 'Chat/process.php',
data : {
'function' : 'getState',
'filename' : 'data/chat_3_1.txt',
},
dataType: 'json',
success: function(data){
myMessages = data.state;
messageArray[3] = {
'filename' : 'chat_3_1.txt',
'divname' : 'msg_3',
'length' : data.state,
};
},
}).done(function(){
delete data;
$.ajax({
type : 'POST',
url : 'Chat/process.php',
data : {
'function' : 'getReadByMe',
'filename' : 'log/chat_3_1_2.txt',
},
dataType: 'json',
success: function(data){
messageArray[3].read = data.read;
},
});
});
instance = false;
return messageArray;
} else {
// setTimeout(checkMessages({}), 500);
}
}
$(document).ready(function(){
console.log('foo');
myMessageArray = checkMessages([]);
console.log(myMessageArray);
$.each(myMessageArray, function(i, obj){
console.log('compare?');
// compareRead(Number(obj['length']), Number(obj['read']), obj['divname']);
});
// setInterval(checkMessages(), 500);
});