javascript - 如何清空数组?

标签 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 = [];但是那个剂量起作用了

最佳答案

重置数组的快捷方式:ids.length = 0;。所以

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

关于javascript - 如何清空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9800104/

相关文章:

Javascript onclick 事件可以显示但不能隐藏

php - MySQL更新和插入-随机不会插入

java - 随机性水平

javascript - jQuery UI 自动完成功能只能运行一次

PHP:返回数组的第一个/最后一个 N 个元素的任何函数

javascript - 将 JSON 响应转换为 map

php - 在php中从另一个数组创建一个数组

javascript - JavaScript 中的 PHP 变量属性

javascript - 单个 div 的视差效果

javascript - 保存 promise 的变化变量