Javascript 如何创建jquery对象数组

Javascript 如何创建jquery对象数组,javascript,jquery,arrays,Javascript,Jquery,Arrays,我的项目中有城市对象。我想用一些城市对象创建一个jquery数组。我可以从.ashx文件中获取城市列表并创建单个城市对象。但我无法将它们推到阵列中。这是我的密码: var postDataCity = { funcName: "GetCities" }; var cities = []; var city = {}; $.ajax({ type: "POST", contentType: "ap

我的项目中有城市对象。我想用一些城市对象创建一个jquery数组。我可以从.ashx文件中获取城市列表并创建单个城市对象。但我无法将它们推到阵列中。这是我的密码:

 var postDataCity = { funcName: "GetCities" };

        var cities = [];
        var city = {};

        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "json",
            url: "KurumInformation.ashx",
            data: postDataCity,
            async: true,
            success: function (msg) {
                $.each(msg, function (i, v) {
                    city.M_CityId = this.M_CityId ;
                    city.M_CityName= this.M_CityName;
                    cities.push(city);
                });
            },
            error: function (d) {
                alert('error :' + d);
            },
        });

        console.log(cities);

在此之后,我检查了城市,但我认为有一个错误,因为我无法在控制台中看到城市。我的错误在哪里?

在回调AJAX调用之前显示变量。您应该在回调函数中包含您的console.log()。

您的代码几乎没有问题,您必须在循环中声明
city

此外,您只需在按下后移动
控制台.log
,即可查看结果:

success: function (msg) {
    $.each(msg, function (i, v) {
        var city = {};   //Move declaration here
        city.M_CityId = this.M_CityId ;
        city.M_CityName= this.M_CityName;
        cities.push(city);
    });
    console.log(cities);   //Move it here
},
如果在外部声明,则每次都将向数组中添加相同的城市引用

另外,由于ajax调用是异步的,所以旧的
console.log
会在ajax调用完成之前执行,这就是为什么会看到空结果

干杯

它会很好地工作。

它可能是异步的,console.log在填充数组之前执行,因为ajax就是这样工作的。
$.each(msg, function (i, v) {
       city.M_CityId = v.M_CityId ;
       city.M_CityName= v.M_CityName;
       cities.push(city);
});