delete object.property;
delete object['property'];
delete array[index];
回傳 true(刪除成功或屬性不存在),false(嚴格模式下不可配置屬性失敗)。
const a = { pro: 'zhenn' };
const o = { c: a };
delete o.c;
console.log(o.c); // undefined(屬性移除)
console.log(a.pro); // 'zhenn'(物件 a 仍存在,未被垃圾回收)
結論:delete 僅切斷「屬性名 → 值」的繫結,值本身若仍被其他引用持有則不會被 GC 回收。
const arr = [1, 2, 3];
delete arr[1];
console.log(arr); // [1, empty, 3] (Chrome 顯示 empty)
console.log(arr.length); // 3
console.log(1 in arr); // false
console.log(arr[1]); // undefined
對比 arr.splice(1,1):真正移除元素,長度變 2,後續元素前移。
var a = 1;
delete a; // false (非嚴格模式) / SyntaxError (嚴格模式)
console.log(a); // 1
function fn() { return 42; }
delete fn; // false
console.log(fn()); // 42
b = 2; // 隱式全域變數(無 var/let/const)
delete b; // true!!
console.log(b); // ReferenceError: b is not defined
每個屬性擁有內部屬性 [[Configurable]]:
true:可 delete、可修改屬性描述符。false:不可刪除(Object.defineProperty 設定、內建物件某些屬性、var/function 宣告的全域/函數作用域變數)。'use strict';
var x = 1;
delete x; // SyntaxError: Delete of an unqualified identifier in strict mode.
const obj = { x: 1 };
Object.defineProperty(obj, 'y', { value: 2, configurable: false });
delete obj.y; // TypeError: Cannot delete property 'y'
delete obj.prop。splice、filter、pop/shift,不要用 delete。null / undefined,解除引用讓 GC 回收,而非 delete。Map / Set,提供 delete(key)、clear()、size 等語義清晰的 API。delete 專為**物件屬性**設計,對陣列會產生稀疏洞,對變數受作用域與 [[Configurable]] 限制極大。理解其「斷開繫結」本質,避免誤用於陣列或變數釋放。