delete 是項目中使用頻率並不很高的一個操做,可是某些狀況下,delete 的操做結果與我設想的不太同樣。express
通常狀況下,使用 delete 刪除一個對象的某個屬性時:數組
delete expression函數
其中 expression 的計算結果是某個屬性的引用this
const Employee = {
firstname: 'John',
lastname: 'Doe'
}
console.log(Employee.firstname); // > "John"
delete Employee.firstname;
console.log(Employee.firstname); // > undefined
複製代碼
返回 truespa
屬性不可配置時,非嚴格模式返回 false ,嚴格模式拋出語法錯誤prototype
var Employee = {};
Object.defineProperty(Employee, 'name', {configurable: false});
console.log(delete Employee.name); // > false
複製代碼
屬性不存在時,依然返回 true ,只是 delete 語句沒什麼做用code
var Employee = {
age: 28,
name: 'abc',
designation: 'developer'
}
console.log(delete Employee.name); // > true
console.log(delete Employee.salary); // > true
複製代碼
delete 只對對象自身屬性起做用,不能刪除原型鏈上的屬性對象
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
複製代碼
使用 var 聲明的屬性都是不可配置的, delete 不能刪除ip
var nameOther = 'XYZ'; // window.nameOther = ‘XYZ’
Object.getOwnPropertyDescriptor(window, 'nameOther');
// > Object {value: "XYZ",
// writable: true,
// enumerable: true,
// configurable: false}
delete nameOther; // > false
複製代碼
不使用 var 、let、const 建立的全局做用域屬性能夠被 delete 刪除內存
adminName = 'xyz'; // window.adminName = ‘xyz’
Object.getOwnPropertyDescriptor(window, 'adminName')
// > Object {value: ‘xyz’,
// writable: true,
// enumerable: true,
// configurable: true}
delete adminName; // > true
複製代碼
delete 不能刪除全局做用域中的函數,不能刪除任何做用域中的 let const 聲明的屬性
function f() {
var z = 44;
console.log(delete z);
}
f() // >false
delete f // >false
複製代碼
delete 不能刪除內建靜態屬性
delete Math.PI // > false
複製代碼
刪除數組元素時,數組長度不受影響,但被刪除的元素再也不屬於該數組,且 delete 操做並不能直接釋放內存。
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", empty,」maple"]
複製代碼