gpt4 book ai didi

javascript - 无法读取未定义类型的属性 'push' 错误 : Cannot read property 'push' of undefined error

转载 作者:行者123 更新时间:2023-12-01 03:54:06 28 4
gpt4 key购买 nike

我定义了一个 JS 数组如下:

var forecastJSArray=new Array();

然后我尝试使用推送将我的 json 对象添加到该数组中,如下所示:

$.getJSON("api-detail.json")
.then(function (forecast){
$.each(forecast, function() {
self.forecastJSArray.push({
rank: this.rank,
rep: this.rep,
total: this.total,
});
});
})
;

但是当我运行这段代码时,它给我一个错误:无法读取未定义的属性“push”TypeError:无法读取未定义的属性“push”

我的最终数组应如下所示:

[
{
"rank" : 1,
"rep" : "rep1",
"total" : 10,
}, {
//...etc
}
]

如果有人能告诉我我哪里出了问题,我将非常感激。预先非常感谢。

编辑:代码包含在 oracle-jet View 模型中(它使用 knockoutjs View 模型),就像这样,带有 RequireJS block :

define(['ojs/ojcore', 'knockout', 'jquery', 'ojs/ojselectcombobox', 
'ojs/ojtable', 'ojs/ojbutton'], function(oj, ko, $) {

function DashboardViewModel() {
var self = this;
... earlier code
... earlier code
}
return new DashboardViewModel();
});

由于 $.getJSON 异步返回,我发现很难在回调函数之外使用数据。所以尝试先将数据推送到JS数组中。如果您需要任何其他信息,请告诉我。 TIA。

最佳答案

首先,从您这边无法了解您是否在任何地方定义了 self

其次,您创建了一个数组forecastJSArray

您可以尝试删除 self 并直接引用数组

forecastJSArray.push({
rank: this.rank,
rep: this.rep,
total: this.total,
});

关于javascript - 无法读取未定义类型的属性 'push' 错误 : Cannot read property 'push' of undefined error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42918858/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com