【问题标题】:Typescript and Javascript Array not showing length property [closed]打字稿和Javascript数组不显示长度属性[关闭]
【发布时间】:2022-11-02 20:36:16
【问题描述】:

我有一个复杂的接口,它的属性是数组,它看起来像这样:

export interface Fundamentals {
BookValue: number;
EarningsQuarterly: EarningsQuarter[];
}

在我的代码中,我像这样从 json 加载接口

this.jsonData = JSON.parse(this.selectedSymbol.fundamentalJson);

this.fndFundamentals.EarningsQuarterly = <EarningsQuarter[]>this.jsonData.Earnings.History;

当我编写控制台时,我看到 this.fndFundamentals.EarningsQuarterly 具有值。

但是,当我尝试写

this.fndFundamentals.EarningsQuarterly.length 

它显示为“未定义”。

当我尝试

this.fndFundamentals.EarningsQuarterly.map(x => x.EpsEstimate) 

我收到地图不存在的错误。

控制台在控制台中打印 this.fndFundamentals.EarningsQuarterly 值,所以我知道它已加载。见下文

{
    "2023-06-30": {
        "ReportDate": "2023-07-26T00:00:00+00:00",
        "EpsEstimate": null,
        "EpsDifference": null,
        "SurprisePercent": null,
        "Date": "2023-06-30T00:00:00+00:00",
        "EpsActual": null
    },
    "2023-03-31": {
        "ReportDate": "2023-04-26T00:00:00+00:00",
        "EpsEstimate": null,
        "EpsDifference": null,
        "SurprisePercent": null,
        "Date": "2023-03-31T00:00:00+00:00",
        "EpsActual": null
    },
    "2022-12-31": {
        "ReportDate": "2023-02-09T00:00:00+00:00",
        "EpsEstimate": "-1.62",
        "EpsDifference": null,
        "SurprisePercent": null,
        "Date": "2022-12-31T00:00:00+00:00",
        "EpsActual": null
    }
}

我究竟做错了什么?

【问题讨论】:

  • What am i doing wrong?所有线索都表明这不是一个数组
  • ^ 您可以注销this.fndFundamentals.EarningsQuarterly 的值并将其编辑到您的问题中吗?
  • 在 JavaScript 世界中,我们说“如果它像鸭子一样走路,它会像鸭子一样叫,它会像鸭子一样游泳,那么它就是鸭子”。你的代码没有嘎嘎作响
  • 显然,this.selectedSymbol.fundamentalJson 中的 JSON 没有定义具有 Earnings 属性的对象,该属性具有数组的 History 属性。但是如果没有看到 JSON,就不可能说它是什么。你说它“有价值”,但没有说你所看到的让你这么想。它可以定义一个看起来有点像数组的非数组对象:{"0": "zero", "1": "one"}。但...
  • 我添加了控制台的输出。它显示正确加载的对象

标签: javascript arrays typescript dictionary


【解决方案1】:

我知道它已经加载了。见下文

{ 
    "2023-06-30": {

所以它不是一个数组,它是一个键值字典。如果你想得到相当于 length 的那个,你可以,例如,做 Object.values(this.fndFundamentals.EarningsQuarterly).length

【讨论】:

    猜你喜欢
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多