In the project, some objects need to be reset after they are used up. The following is a brief introduction to the method of clearing objects in JS. Methods as below:
Method 1: Literal definition object
The first step, define an empty object and print it out, code and effect:
Code:
var student = {};
console.log(student);
print result:
The second step, add attributes to the object and print, the code and print results are as follows:
Code:
student.name = "xiaoming";
student.age = 12;
console.log(student);
print result:
The third step, delete the object attribute (empty the object) and print, the code and print result are as follows:
Code:
for(var key in student){
delete student[key];
}
console.log(student);
print result:
It can be seen that after the object is emptied, it becomes an empty object again, realizing the object reset.
All JS code:
Results of the:
Method 2: The constructor defines the object
Code:
print result: