jQuery多维数组(动态键) - 无法设置未定义

时间:2016-09-28 21:07:24

标签: javascript jquery arrays multidimensional-array

感谢Chad的解决方案,但现在它似乎清除了数组中的值,这是控制台日志中的foreach,它显示了我的情况(后面是更新函数的更新代码):

timer.html:60 ------------------------------------
timer.html:57 0
timer.html:58 undefined
timer.html:57 1
timer.html:58 1.910
2timer.html:60 ------------------------------------
timer.html:57 0
timer.html:58 undefined
timer.html:57 1
timer.html:58 undefined
timer.html:57 2
timer.html:58 1.727
2timer.html:60 ------------------------------------
timer.html:57 0
timer.html:58 undefined
timer.html:57 1
timer.html:58 undefined
timer.html:57 2
timer.html:58 undefined
timer.html:57 3
timer.html:58 0.690
timer.html:60 ------------------------------------

=============================================

function updateLap(kartId){

  if (isNaN(driverLapNumber[kartId])) {
     //IF LAP NOT SET THEN THE KART ID NEEDS TO BE SET AS 0 AS IT IS THE START OF THE RACE
     window.driverLapNumber[kartId] = 0;  
  }

  //ADD ONE LAP TO THE KART ID
  driverLapNumber[kartId]++;

  //ADD LAP TIME FOR CURRENT LAP NUMBER  
  driverLapTimes[kartId] = [];
  driverLapTimes[kartId][driverLapNumber[kartId]] = window.lapTime;

   $.each(driverLapTimes , function( index, obj ) {
    $.each(obj, function( key, value ) {
        console.log(key);
        console.log(value);     
    });
    console.log("------------------------------------");
  });


  $(".lapTimes").prepend("kartId: "+kartId+" - "+window.lapTime+"<br>");

}

我想我可以为此归咎于PHP,因为我可能会按照我目前的写作方式,我需要帮助来纠正这个问题。

一切都很好,除了driverLapTimes数组上的SECOND键,我希望它输出如下内容:

driverLapNumber[999][1] = 6.666;
driverLapNumber[999][2] = 6.666;
driverLapNumber[999][3] = 6.666;
driverLapNumber[999][4] = 6.666;

但1,2,3,4键出现以下控制台错误:

  

未捕获的TypeError:无法设置属性&#39; 1&#39;未定义的

功能代码:

function updateLap(kartId){

  if (isNaN(driverLapNumber[kartId])) {
     window.driverLapNumber[kartId] = 0;  
  }

  //ADD ONE LAP TO THE KART ID
  driverLapNumber[kartId]++;

  //ADD LAP TIME FOR CURRENT LAP NUMBER
  driverLapTimes[kartId][driverLapNumber[kartId]] = window.lapTime;  

}

2 个答案:

答案 0 :(得分:3)

在这种情况下,数组项可能尚未声明为新数组。试试这个:

function updateLap(kartId){



if (isNaN(driverLapNumber[kartId])) {
     window.driverLapNumber[kartId] = 0;  
  }

  //ADD ONE LAP TO THE KART ID
  driverLapNumber[kartId]++;

  //ADD LAP TIME FOR CURRENT LAP NUMBER
  if(!driverLapTimes[kartId]){
       driverLapTimes[kartId] = [];
  }
  driverLapTimes[kartId][driverLapNumber[kartId]] = window.lapTime;  

}

当然,您可以通过创建一个预先构建数组的方法,将声明放在此循环之外。

答案 1 :(得分:0)

请尝试以下方式告诉我

var a = new Array();
a[0]= new Array();
a[0].push(1);
a[0].push(2);
a[0].push(3);

console.log(a[0][0]);
console.log(a[0][1]);
console.log(a[0][2]);