Wednesday, 11 September 2013

Array push doesnt work the first time

Array push doesnt work the first time

I have the following code to run a function every second
var counter=setInterval(timer, 1000);
var global = [];
function timer()
{
var strJSON = '[{"id":"1","timeout":"2013-09-11
03:00:00"},{"id":"2","timeout":"2013-09-11 03:00:00"}]';
var currentRequest = [];
var obj = jQuery.parseJSON(strJSON);
for (var i=0; i<obj.length; i++) {
var id = obj[i].id;
var timeout = obj[i].timeout;
if(id in global)
{
alert(id+' in array');
} else {
alert(id+' not in array');
alert(id+' added');
global.push(id);
}
}
}
Im using it to keep the global variable updated but without duplicates.
However, when the script runs, the second id is said to be added in the
first run but it is not really added as i get the following output:
/** FIRST RUN **/
1 not in array
1 added
2 not in array
2 added
/** SECOND RUN **/
1 in array
2 not in array
2 added
/** THIRD RUN **/
1 in array
2 in array
What am i doing wrong here?

No comments:

Post a Comment