代码之家  ›  专栏  ›  技术社区  ›  Mike

从JQuery每个函数中的对象获取值

  •  0
  • Mike  · 技术社区  · 8 年前

    我有一个包含关联数组的对象

    enter image description here

    存储在数组中的值是一个对象

    在each函数中,我想访问value对象中的一个值( responseText )

    enter image description here

    我的代码如下

     var apiNameArray = getDataSourceApiNames();
            var apiResults = {};
            var deferred;
    
            for (let i = 0; i < apiNameArray.length; i++) {
                var apiName = apiNameArray[i];
                console.log("apiName = " + apiName);
                deferred = $.ajax({
                        type: "GET",
                        url: api_URL + "memberdetails/" + memberNumber,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json"
                    }
                );
                apiResults[apiName] = deferred;
            }
    
            $.when.apply($, apiResults).then(function () {
                console.log(apiResults);
                $.each(apiResults, function (key, value) {
                    console.log(key);
                    console.log(value);
                    console.log(value.responseText);
               });
            });
    

    出于某种原因, value.responseText 正在返回未定义。我应该如何访问此值/属性?我试过了 value["responseText"] , apiResults[key].responseText 都没有成功

    1 回复  |  直到 8 年前
        1
  •  1
  •   karan3112    8 年前

    作为 apiResults 是一个可以在关键点之间循环并使用的对象 apiResults[key].responseText 访问该值。

    $.when.apply($, apiResults).then(function () { $.each(apiResults, function (key, value) { console.log(apiResults[key].responseText); }); });

    $.when.apply($, apiResults).then(function () { Object.keys('apiResults').forEach(function(item, index){ console.log(apiResults[item].responseText) }) });

    在这里 Object.keys 将返回对象中所有键的数组。