为什么我的 const 变量输出不是空的

Why is my const variable output, not empty

这可能很愚蠢,但我阅读代码的时间太长了,似乎无法找到为什么我的变量没有在控制台中打印为空,如果它没有到达实际将值推入的函数它。效果很好,我只是想知道为什么。

我打印了很多 console.log 来跟踪我填充变量(它是一个数组)的任何代码行,我还在代码的其他部分尝试了不同的东西,但它是一个 const 变量,因此可以从函数外部为其分配不同的值。

function ABC() {

  console.log('FUNCTION BEGINS...');
  const tempDates: Array<Moment> = [];
  console.log(tempDates);
  console.log('After creating the variable...');

  console.log('Before log tempdates');
  console.log(tempDates);

  const start_date = this.date;

  let dateToAdd = start_date;
  tempDates.push(dateToAdd);

  console.log(dateToAdd);
  console.log(tempDates);
}

也许我错了,过度分析了,但我希望我第一次打印 const 'tempDates' 时打印一个空数组。但实际上输出里面有3个日期的数组,如果条件为真,实际上会填充这些日期,之后有很多行代码。

控制台是这样的:

这是因为现在 Chrome 控制台处理对象的方式。它实际上会打印一个指向该对象内容的指针——如果内容发生变化,控制台中的输出也会发生变化。为了在控制台中准确查看对象或数组在给定时间点的样子,请务必在 console.log() 语句中使用 JSON.stringify().toString() 进行转换它是一个不会改变的字符串。

console.log(JSON.stringify(myArray))

console.log(myArray.toString())

Here's an article explaining this 如果你有兴趣。

也就是说,您的代码按预期工作,Chrome 只是具有欺骗性。