控制台日志显示数组的特定值 'undefined'

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]arr[1]arr[2]...)?

我认为你打电话 console.log 太早了。 console.log(arr) 只有效,因为记录了对该数组的引用,一旦 renderDay 为 运行 就会更新。在此处查看 MDN:console.log documentation

Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you open the console.

尝试记录 arr[0] 在您在代码中某处调用 renderDay 之后

您也可以尝试用 console.log(arr.toString()) 替换 console.log(arr) 以获得 arr 在您记录它的确切时刻的值 - 在 [= 之前​​被调用时它应该是空的12=] 是 运行.