【问题标题】:Cannot read property 'push' of undefined TypeError: Cannot read property 'push' of undefined error无法读取未定义类型错误的属性“推送”:无法读取未定义错误的属性“推送”
【发布时间】:2017-08-12 15:09:44
【问题描述】:

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

var forecastJSArray=new Array();

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

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

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

我的最终数组应该是这样的:

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

如果有人能告诉我我哪里出了问题,我将不胜感激。提前非常感谢。

编辑: 代码包含在一个 oracle-jet 视图模型(使用 knockoutjs 视图模型)中,类似于这样,带有一个 RequireJS 块:

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.

标签: javascript jquery arrays json


【解决方案1】:

首先,从您的角度来看,您无法理解您是否在任何地方定义了self

其次,你已经创建了一个数组forecastJSArray

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

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

【讨论】:

    【解决方案2】:

    var forecastJSArray 在函数范围或全局范围内定义forecastJSArray

    self.forecastJSArray 仅在 self 引用 windowforecastJSArray 定义在全局范围内时才有效。一般来说,您不应该在全局范围内定义变量。

    TypeError: 无法读取未定义的属性“push”

    告诉你selfundefined(不持有任何值)。

    因此,如果var forecastJSArray 定义在$.each(forecast, function() { 回调中的代码的可达范围内,那么您将编写:forecastJSArray.push 没有self.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多