1. The sequence

When writing code, we often print information in the console in the form of console.log() to help with front-end debugging. In general, we can print normal values with no problem, but we need to be careful when printing object types, otherwise we may get unexpected results.

2. Console. log() output object property is missing

  • First of all, we define aThe cat objectAnd it has aname, age, color, birthdayFour properties.
  • And then we define a functiontest, which takes an object as a parameter. When calling the test function, we want to know what parameters are passed to the test functionconsole.log(obj)Print out the passed object, and finally delete the passed object somewhere within the functionnameProperties.

If you call test with the cat object as an argument, what will the console print? Is it going to be what we expect the argument to look like when we pass it in?

const cat = {
    name: 'meow meow'.age: '2'.color: 'white'.birthday: 'January 1st'
}

function test(obj) {
    console.log(obj)
    // There is a long code...
    delete obj.name
}

test(cat)
Copy the code

Console output:

name
name
delete obj.name
name

3. Get the right results

Since the result of expanding console.log() is not a copy of the object at that point in time when our code is at that point in time, we want the state of the object at that point in time when our code is executed, simply by printing a copy of the object at that point in time.

3.1 Method 1: Expand objects

const cat = {
    name: 'meow meow'.age: '2'.color: 'white'.birthday: 'January 1st'
}

function test(obj) {
    console.log({... obj})// Get a copy of obj using ES6's object expansion operator.
    // There is a long code...
    delete obj.name
}

test(cat)
Copy the code

At this point, we get the state of obj at the console.log() point in time.

3.2 Method 2: json.stringfy () Look at the string

const cat = {
    name: 'meow meow'.age: '2'.color: 'white'.birthday: 'January 1st'
}

function test(obj) {
    console.log(JSON.stringify(obj))  // Call the json.stringify () method to convert the object to a string
    // There is a long code...
    delete obj.name
}

test(cat)
Copy the code

Again, we can get the state of the OBJ object at the point in time the code was running.

conclusion
The first method is recommended