[英]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: 但是,当脚本运行时,第二个ID据说是在第一次运行中添加的,但由于我得到以下输出,因此它并不是真正添加的:
/** FIRST RUN **/ /** 首轮 **/
/** SECOND RUN **/ / **第二次运行** /
/** THIRD RUN **/ / **第三次运行** /
What am i doing wrong here? 我在这里做错了什么?
id in global
is not used to check an element in an array. id in global
不用于检查数组中的元素。 You need to use .indexOf
instead. 您需要改用.indexOf
。
> "1" in ["1","2"]
true
> "2" in ["1","2"]
false
property in object
is to check whether an property exist in an object. property in object
中的属性是检查property in object
中是否存在属性。
Array is 0-indexed, so "0" in ["1","2"]
and "1" in ["1", "2"]
would be true, but not "2"
. 数组是0索引的,因此"0" in ["1","2"]
"1" in ["1", "2"]
为true,但不是"2"
。
So you need to change 所以你需要改变
if(id in global)
to 至
if (global.indexOf(id) > -1)
Note: You need a shim for old browsers which doesn't support indexOf
method of array. 注意:对于旧的浏览器,您需要一个垫片,它不支持array的indexOf
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.