【问题标题】:Developer Tools Console showing only final values仅显示最终值的开发者工具控制台
【发布时间】:2021-12-15 04:57:50
【问题描述】:

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

// 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)

在所有添加的项目上显示“测试我 4”,因此不仅仅是日志记录。

发生了什么事?如何查看进度并查看准确的值,并将正确的值附加到数组中?

【问题讨论】:

    标签: javascript microsoft-edge developer-tools


    【解决方案1】:

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

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

    发生这种情况是因为当您分配 bar = foo 时,您实际上并没有创建 foo 的 副本。相反,您是说,这个变量 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 2012-08-27
      • 2017-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      相关资源
      最近更新 更多