You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中读取对象数组?获取值时显示undefined

问题:JavaScript对象数组取值显示undefined,如何正确读取?

我在JavaScript中有一个对象数组,但尝试获取特定值时一直显示undefined,想了解如何读取该数组中的值。

代码示例

function approveOrRejectTRF(primaryControl) {
    'use strict';
    if (!primaryControl) { return; }
    var formContext = primaryControl;
    var Id = formContext.data.entity.getId();

    var pageInput = {
        pageType: "webresource",
        webresourceName: "hsl_/html/TravelRequest/ApproveRejectButtonHtml.html",
        data: "&EntityId=" + Id
    };
    var navigationOptions = {
        target: 2,
        width: 800,
        height: 450,
        position: 1,
        title: "Approve/Reject"
    };
    Xrm.Navigation.navigateTo(pageInput, navigationOptions).then(
        function success(returnValue) {
            console.log(returnValue);
            console.log("Action : " + returnValue[0].actionVal);
            console.log("Comments : " + returnValue[0].commentsVal);
        },
        function error(e){
            // Handle errors
        }
    );
}

调试信息

调试器显示returnValue是一个直接包含actionVal和commentsVal属性的单个对象,并非你预期的数组结构。


解决方法

核心问题是你错误地将returnValue当作数组使用(通过returnValue[0]访问),但它本质是一个普通对象。

修改success回调中的代码,移除数组索引[0],直接访问对象属性即可:

function success(returnValue) {
    console.log(returnValue);
    console.log("Action : " + returnValue.actionVal);
    console.log("Comments : " + returnValue.commentsVal);
}

如果后续不确定返回值的结构,可通过以下代码在控制台打印相关信息,确认其类型和属性:

console.log(typeof returnValue); // 查看返回值类型
console.log(Object.keys(returnValue)); // 查看返回值包含的所有属性名

内容的提问来源于stack exchange,提问作者gymcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 23:54:59