【发布时间】: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