jQuery, JSON数组推送

jQuery, JSON array push

我在完成这项工作时遇到了一点问题:

这是我通过 ajax:

提取的 json 数组
{
    "message": [{
        "title": "Account",
        "id": 1
    }, {
        "title": "Content",
        "id": 2
    }, {
        "title": "Other",
        "id": 3
    }]
}

这里是javascript:

var items = [];
$.get("settings.php", {
        getlink: 1,
    }, function(json) {
        $.each(json.message, function() {
            items.push(this);
        });

},"json");

console.log(items)

但由于某些原因,项目数组始终为空[] 我可以在 firebug、json 中看到返回的数组,但我无法推送它。

使用 index, value$.each return :

$.each(json.message, function(index, value) {
    items.push(value);
});

注意: $.each() 不同于 .each().

希望对您有所帮助。

您需要将参数传递给 $.each 函数并将该对象推送到您的数组。

var json = {
    "message": [{
        "title": "Account",
        "id": 1
    }, {
        "title": "Content",
        "id": 2
    }, {
        "title": "Other",
        "id": 3
    }]
}

var items = [];
$.each(json.message, function(index, item) {
  items.push(item);
});

console.log(items)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>