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

2023-12-07

感谢乍得的解决方案,但是现在似乎清除了数组中的值,这是一个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数组,我希望它输出如下内容:

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

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

未捕获的类型错误:无法设置未定义的属性“1”

功能代码:

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;  

}

当然,您始终可以通过创建一个方法来预先构造数组,从而将声明放在该循环之外。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jQuery 多维数组(动态键) - 无法设置未定义的属性 的相关文章

随机推荐