简体   繁体   中英

Developer Tools Console showing only final values

I have the following code that I run in the console:

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

I know that the console doesn't update until the code is finished, so all variables are logged with their final value. I had thought that using different variables would avoid that, but asTheyWere and asTheyAre are the same, showing 55 elements (the first should have 50), AND the values appended to the end of the array are all the same as well: they should be 'test me 0', 'test me 1', 'test me 2' and so on, but they're all 'test me 4'.

When it's all done, then running

> console.log(selDocument.fields.field)

shows 'test me 4' on all added items, so it's not just the logging.

What's going on? How can I watch the progress and see accurate values, and get the right values appended to the array?

Even though they are different variables, they are still pointing to the same value. For example:

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

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

This happens because when you assign bar = foo , you aren't actually creating a copy of foo. Instead, you're saying, this variable bar is just another name used to refer to the contents of foo .

You could try cloning the original object to compare it to the new one. If the object is comprised of simple data, you can clone it like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM