如何清空数组?

时间:2012-03-21 07:15:01

标签: javascript php arrays json ajax

昨天我问一个关于json的问题

链接:How to return an array from jQuery ajax success function and use it in a loop?

其中一个答案就是这个

setInterval(updateTimestamps,30000);
var ids = new Array();

function updateTimestamps(){
    $(".timestamp").each(function(i){
    var obj = new Object();
    obj.id = $(this).attr("postID");
    obj.timestamp = $(this).attr("postdate");
        ids.push(obj);
    }

    $.post("http://site.com/ajax/humanTime.php", {"time": ids}, function(data) {
        for (i = 0; i < data.length; i++) {
            $("#" + data[i].id).html(data[i].content);
        }
    }, "json");
}

此脚本的问题是数据是公开的

第一次执行此操作时

Array
(
    [0] => Array
        (
            [id] => 26629
            [timestamp] => 1332273712
        )

    [1] => Array
        (
            [id] => 26628
            [timestamp] => 1332243526
        )

    [2] => Array
        (
            [id] => 26627
            [timestamp] => 1332237777


)

第二次是

Array
(
    [0] => Array
        (
            [id] => 26629
            [timestamp] => 1332273712
        )

    [1] => Array
        (
            [id] => 26628
            [timestamp] => 1332243526
        )

    [2] => Array
        (
            [id] => 26627
            [timestamp] => 1332237777
        )

    [3] => Array
        (
            [id] => 26629
            [timestamp] => 1332273712
        )

    [4] => Array
        (
            [id] => 26628
            [timestamp] => 1332243526
        )

    [5] => Array
        (
            [id] => 26627
            [timestamp] => 1332237777
        )

)

我尝试使用var ids = Array(); ,vas ids = [];但那个剂量工作

5 个答案:

答案 0 :(得分:3)

在开始推送项目之前设置ids = []。这是你的代码,重新考虑:

var ids;

function updateTimestamps() {
    ids = []; // <-- the answer
    $(".timestamp").each(function(i) {
        ids.push({
            id: $(this).attr("postID"),
            timestamp: $(this).attr("postdate")
        });
    });
    $.post("http://site.com/ajax/humanTime.php", {"time": ids}, function(data) {
        for (var i = 0; i < data.length; i++) {
            $("#" + data[i].id).html(data[i].content);
        }
    }, "json");
}

setInterval(updateTimestamps, 30000);​

答案 1 :(得分:3)

重置数组的简短方法:ids.length = 0;。所以

function updateTimestamps(){
  ids.length = 0;
  // [...]
}

答案 2 :(得分:2)

试试这个:

var ids;

function updateTimestamps(){
  ids = [];
   ...

答案 3 :(得分:2)

function updateTimestamps(){

添加

ids = [];

答案 4 :(得分:2)

setInterval(updateTimestamps,30000);

function updateTimestamps(){
    var ids = []; // put it here

    $(".timestamp").each(function(i){
    var obj = {};
    obj.id = $(this).attr("postID");
    obj.timestamp = $(this).attr("postdate");
        ids.push(obj);
    }

    $.post("http://site.com/ajax/humanTime.php", {"time": ids}, function(data) {
        for (i = 0; i < data.length; i++) {
            $("#" + data[i].id).html(data[i].content);
        }
    }, "json");
}