簡體   English   中英

控制台日志顯示數組的特定值的“未定義”

[英]Console log shows 'undefined' for a specific value of an array

我試圖將與當前月份的星期日和星期六對應的值存儲在一個數組 ( arr ) 中並將其顯示在控制台中,變量 'd' 表示當月的天數。

當我嘗試顯示像console.log(arr[1])這樣的特定值時,它在控制台中顯示“未定義”。

  let arr = []; 
  console.log(arr)
  console.log(arr[0]);

  const renderDay = () => {
         let td = [];
         for (let i = 1; i <= d; i++) {
          if(days[i].toLocaleDateString("fr-FR", options).slice(0,3)==='sam' ||
          days[i].toLocaleDateString("fr-FR", options).slice(0,3)==='dim'){
             td.push(<td className="test" key={i}>{days[i].toLocaleDateString("fr-FR", options).slice(0,3)}</td>);
             arr.push(i);
          }else
             td.push(<td key={i}>{days[i].toLocaleDateString("fr-FR", options).slice(0,3)}</td>);
            }
      return td;
       };

我想檢查數組是否為空,所以我用console.log(arr)顯示整個數組,輸出看起來不錯,它顯示了一個長度為: 8 arr = {0: 6 , 1: 7 , 2: 13 , 3: 14 , 4: 20 , 5: 21 , 6: 27 , 7: 28}的數組arr = {0: 6 , 1: 7 , 2: 13 , 3: 14 , 4: 20 , 5: 21 , 6: 27 , 7: 28} ,代表當月周六周日的索引,但是我無法通過索引訪問每個特定值。

如何通過索引( arr[0]arr[1]arr[2] ....)訪問每個特定值?

我認為您過早地調用了console.log console.log(arr)僅有效,因為記錄了對該數組的引用,並在renderDay運行后立即更新。 在此處檢查 MDN: console.log 文檔

請注意,如果您在最新版本的 Chrome 和 Firefox 中記錄對象,則您在控制台上記錄的是對對象的引用,這不一定是您調用 console.log 時對象的“值”。 log(),但它是您打開控制台時對象的值。

在代碼中的某處調用renderDay后,嘗試記錄arr[0]

您還可以嘗試將console.log(arr)替換為console.log(arr.toString())以獲取arr在您記錄它的確切時刻的值 - 在運行renderDay之前renderDay時它應該為空。

暫無
暫無

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

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