开发人员工具控制台仅显示最终值

Developer Tools Console showing only final values

我在控制台中 运行 有以下代码:

// cache the starting array - 50 elements
let asTheyWere = selDocument.fields.field;
// create the new object
let nf = {};
$j.each(selDocument.fields.field[selDocument.fields.field.length - 1], function(a, b){
    nf[a] = b;
});
// make a change and add the object to the array
for(i = 0; i < 5; i++) {
    nf.name = `test me ${i}`;
    // console.log(nf.name) shows 'test me 0', 'test me 1' ... 'test me 4'
    selDocument.fields.field.push(nf);
}
// assign the array to a new variable - now at 55 elements
let asTheyAre = selDocument.fields.field;
// check the values
console.log(asTheyWere);
console.log(asTheyAre);

我知道在代码完成之前控制台不会更新,所以所有变量都用它们的最终值记录。我原以为使用不同的变量可以避免这种情况,但 asTheyWere 和 asTheyAre 是相同的,显示 55 个元素(第一个应该有 50 个),并且附加到数组末尾的值也都是相同的:它们应该是'test me 0'、'test me 1'、'test me 2'等等,但都是'test me 4'.

全部完成后,运行宁

> console.log(selDocument.fields.field)

显示 'test me 4' 所有添加的项目,因此不仅仅是日志记录。

这是怎么回事?如何查看进度并查看准确的值,并将正确的值附加到数组?

即使它们是不同的变量,它们仍然指向相同的值。例如:

const foo = ['hello']
const bar = foo

foo[0] = 'goodbye'
console.log(bar[0]) // prints "goodbye"!

发生这种情况是因为当您分配 bar = foo 时,您实际上并没有创建 foo 的 copy。相反,你是说,这个变量 bar 只是用来 引用 foo.

内容的另一个名称

您可以尝试克隆 原始对象以将其与新对象进行比较。如果对象由简单数据组成,您可以像这样克隆它:

const asTheyWere = JSON.parse(JSON.stringify(selDocument.fields.field));
// Make your changes...
const asTheyAre = selDocument.fields.field;

console.log(asTheyWere);
console.log(asTheyAre);