为什么 console.log() 创建 /**id:4**/ 和 /**ref:4**/ 值?

why console.log() creating /**id:4**/ and /**ref:4**/ values?

几分钟前我做了 this answer,答案片段在

下面

let obj = {staff_changes: []};
let newStaff=[];
for (let i = 0; i < 4; i++) {
 newStaff.push({id: 'staff' +i});
 obj.staff_changes.push({
  id: i,
  newStaff: newStaff
 });
}
console.log(obj);

如果您 运行 以上代码段,您可以看到 /**id:4**//**ref:4**/ 。这是什么?

当代码执行时,将相同的重复值推入数组。所以我希望在开始时它生成一个 Id:4 并且如果存在相同的重复值,那么就写一个像 /**ref:4**/ 这样的注释,其中 4 表示 Id=:4 这是已经生成。

So I want to know Is my understand is correct?. If my understanding is correct , then how can we avoid this? Shall I use object.assign() before push the value into array to avoid this?

您的数据结构包含对同一对象的多个引用。 console.log 足够聪明,可以缩写输出。

请注意(AFAIK),规范不保证 console.log 的任何特定输出对于不是 String 的实例的对象,因此您不能依赖该输出在整个过程中都是相同的浏览器、版本、月相等

考虑一个像 const a = []; a.push(a); console.log(a) 这样的无限递归数据结构,您更喜欢哪个:您的计算机在打印无限递归数组或 console.log 缩写时锁定?

const a = []
a.push(a)
console.log(a)
// [
//   /**id:1**/
//   /**ref:1**/
// ]

根据您的控制台工具,它们会以不同的方式显示这样的对象。这些评论告诉你在对象的更深处有更多信息。

如果你想以一致的方式查看内部结构,你可以将整个对象字符串化

console.log(JSON.stringify(obj));

在这种情况下你会得到:

{"staff_changes":[{"id":0,"newStaff":[{"id":"staff0"},{"id":"staff1"},{"id":"staff2"},{"id":"staff3"}]},{"id":1,"newStaff":[{"id":"staff0"},{"id":"staff1"},{"id":"staff2"},{"id":"staff3"}]},{"id":2,"newStaff":[{"id":"staff0"},{"id":"staff1"},{"id":"staff2"},{"id":"staff3"}]},{"id":3,"newStaff":[{"id":"staff0"},{"id":"staff1"},{"id":"staff2"},{"id":"staff3"}]}]}

在某些开发人员工具中,您可以在将对象记录到控制台时展开该对象,但上面的字符串输出会在所有工具中一致地显示所有内容。