簡體   English   中英

jQuery多維數組(動態鍵)-無法設置未定義的屬性

[英]jQuery Multidimensional Array (dynamic key) - Cannot set property of undefined

感謝Chad為他提供的解決方案,但是現在看來它可以清除數組中的值,這是控制台日志上的一條foreach ,它向您顯示了我的情況(隨后是update函數的更新代碼):

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:無法設置未定義的屬性“ 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;  

}

當然,您總是可以通過創建一個事先構造數組的方法來將聲明置於此循環之外。

嘗試以下操作,讓我知道

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM