【问题标题】:Unable to access Objects in a JavaScript Array - result is undefined when accessing object by Index无法访问 JavaScript 数组中的对象 - 通过索引访问对象时结果未定义
【发布时间】:2020-07-19 16:18:24
【问题描述】:

在 Ajax 调用导致的数组索引处访问对象时遇到问题。我假设当我写“console.log(data[0])”时会显示索引 0 处的对象,但我没有定义。任何援助将不胜感激。

function getBarChartData() {

        $.ajax({
            url: "/Dashboard/CarClassAvailability",
            type: "GET",
            dataType: "json",
            success: function (data) { 
                console.log(data);
                console.log(data[0]); // this results in undefined


            }
        });       
    }
Chrome Developer tools results

{data: Array(5)}
data: Array(5)
0: {Id: 15, Make: "Chevrolet", Model: "Malibu ", HasAutomaticTransmission: true, SeatingCapacity: 5, …}
1: {Id: 16, Make: "Ford", Model: "Mustang", HasAutomaticTransmission: false, SeatingCapacity: 4, …}
2: {Id: 17, Make: "Mini", Model: "Countryman", HasAutomaticTransmission: false, SeatingCapacity: 5, …}
3: {Id: 18, Make: "Volkswagen", Model: "Jetta", HasAutomaticTransmission: true, SeatingCapacity: 5, …}
4: {Id: 19, Make: "Kia", Model: "Forte", HasAutomaticTransmission: true, SeatingCapacity: 5, …}length: 5__proto__: Array(0)__proto__: Object
(index):315 undefined



【问题讨论】:

  • console.log(data) 将具有键值对的对象输出为 {data: Array(5)},因此您需要访问第零个索引元素作为 data.data[0]跨度>

标签: javascript asp.net model-view-controller


【解决方案1】:

您要查找的 data 数组位于 data 对象内。试试

console.log(data.data[0]);

【讨论】:

  • 谢谢!做到了。
【解决方案2】:

你得到了错误的索引,因为你在成功函数的参数“数据”中有“数据”,请尝试使用:

success: function (data) { //<- this data have a property called data
            console.log(data);
            console.log(data.data[0]); //<-- try this
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2019-01-11
    • 2020-08-14
    • 1970-01-01
    • 2016-05-18
    • 2017-08-13
    相关资源
    最近更新 更多