未捕获的TypeError:无法读取未定义的Javascript的属性'length'

时间:2019-12-31 01:40:19

标签: javascript arrays ajax date

我遇到了一个问题,我无法在javascript中对数据数组调用.length()方法。目的是能够遍历日期时间字符串数组,以便将它们转换为javascript中的日期对象。这是我的代码。

我的数据:

createWindow

ajax调用:

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
  "sales_time_axis": [
    [
      "2019-12-29T10:42:25Z"
    ],
    [
      "2019-12-23T03:13:03Z"
    ],
    [
      "2019-12-23T02:50:51Z"
    ]
  ],

for循环:

$.ajax({
  type: "GET",
  url: endpoint,    
  success: function(data) {
    window.sales_time = data.sales_time_axis
  },
  error: function(error_data) {
    console.log('error')
    console.log(error_data)
  }
})

我已将sales_time声明为全局变量,但是出现此错误:

var sales_time;
var date_array = []

for(i = 0 ; i < sales_time.length ; i++){
  date_array.push(new Date(sales_time[i]))
}

console.log(data_array)

我们将非常感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

可能您正面临异步变量分配问题。尝试将for循环与成功回调一起使用,并遍历在回调参数上接收到的相同sales_time变量。

$.ajax({
  type: "GET",
  url: endpoint,    
  success: function(data){
    var sales_time = data.sales_time_axis;
    var date_array = []
    for(i = 0 ; i < sales_time.length ; i++){
      date_array.push(new Date(sales_time[i]))
    }
    console.log(data_array)
  },
  error: function(error_data){
    console.log('error')
    console.log(error_data)
  }
})

答案 1 :(得分:0)

您需要先等待ajax调用,因为它是异步的

看看以下链接: How to await the ajax request?

答案 2 :(得分:0)

正如其他人指出的那样,ajax是一个异步过程。 Ajax之外的任何内容都将同步运行,这意味着它不会等待数据来临。一种实现方法是,将迭代方法作为ajax成功方法的回调,并以数据作为参数。

$.ajax({
    // SOME CONFIGS HERE
    success: function(result){
        iterate(result);
    }
});

function iterate(data){
    // Do your iteration here
}

或者如果您坚持使用全局变量thing,那么可以这样做

// Assuming all these are inside the same javascript file

var data = []; // Make this a global value inside your file 

$.ajax({
    // SOME CONFIGS HERE
    success: function(result){
        data = result.data;
        iterate(); // Get data, then hit the iterate process
    }
});

function iterate(){
    // Do your iteration here
    data.forEach(() => { // Some process in here });
}

仅在成功完成调用之后,此方法才会调用迭代。不要尝试在成功方法之外调用迭代,否则肯定会得到一个空数组。

如果您的流程依赖于首先完成的承诺,那么您编写代码的心态必须改变。您只需要在诺言已经解决之后才执行下一步,而不仅仅是在诺言尚未解决的情况下运行它。