Delete is an operation that is not used very often in projects, but in some cases, the result of delete is not quite what I expected.
To delete a property of an object:
grammar
delete expression
Where expression is evaluated as a reference to a property
const Employee = {
firstname: 'John',
lastname: 'Doe'
}
console.log(Employee.firstname); // > "John"
delete Employee.firstname;
console.log(Employee.firstname); // > undefined
Copy the code
return
-
Returns true
-
If the property is not configurable, non-strict mode returns false, and strict mode throws a syntax error
var Employee = {}; Object.defineProperty(Employee, 'name', {configurable: false}); console.log(delete Employee.name); // > false Copy the code
-
If the property does not exist, it still returns true, but the delete statement has no effect. Right
var Employee = { age: 28, name: 'abc', designation: 'developer' } console.log(delete Employee.name); // > true console.log(delete Employee.salary); // > true Copy the code
Pay attention to
-
Delete applies only to the object’s own properties and cannot delete properties on the stereotype chain
function Foo() { this.bar = 10; } Foo.prototype.bar = 42; var foo = new Foo(); delete foo.bar; // > true console.log(foo.bar); // > 42 delete Foo.prototype.bar; console.log(foo.bar); // > undefined Copy the code
-
Properties declared with var are not configurable and cannot be deleted by delete
var nameOther = 'XYZ'; / / window. NameOther = "XYZ Object. GetOwnPropertyDescriptor (Windows, 'nameOther'); // > Object {value: "XYZ", // writable: true, // enumerable: true, // configurable: false} delete nameOther; // > falseCopy the code
-
Global scope properties created without var, let, or const can be deleted by delete
adminName = 'xyz'; / / window, adminName = "xyz Object. GetOwnPropertyDescriptor (window, 'adminName') / / > Object {value: 'xyz', // writable: true, // Enumerable: true, // signals: true} Delete adminName; // > trueCopy the code
-
Delete cannot delete a function in global scope. It cannot delete any property declared as let const in scope
function f() { var z = 44; console.log(delete z); } f() // >false delete f // >false Copy the code
-
Delete cannot delete built-in static properties
delete Math.PI // > false Copy the code
-
When an array element is deleted, the array length is not affected, but the deleted element no longer belongs to the array, and the delete operation does not directly free memory.
var trees = ["redwood","bay","cedar","oak","maple"]; delete trees[3]; if (3 in trees) { console.log('will not be printed') } console.log(trees) // > (5)["redwood","bay","cedar", The empty, "maple"]Copy the code