jQuery多维数组(动态键)-不能设置属性undefined



感谢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键会出现以下控制台错误:

Uncaught TypeError: Cannot set property '1' of undefined

功能代码:

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;  
}

在这种情况下,很可能没有将数组项声明为新数组。试试这个:

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;  
}

当然,你总是可以通过创建一个方法来预先构造你的数组,从而把声明放在循环之外。

试试下面的方法,让我知道

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]);

相关内容

  • 没有找到相关文章

最新更新