萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript delete 運算符深度解析:刪除屬性、陣列漏洞與變數刪除怪象

delete 基本語法

delete object.property;
delete object['property'];
delete array[index];

回傳 true(刪除成功或屬性不存在),false(嚴格模式下不可配置屬性失敗)。

核心行為

1. 刪除物件屬性:移除「引用」,非銷毀值

const a = { pro: 'zhenn' };
const o = { c: a };
delete o.c;
console.log(o.c);     // undefined(屬性移除)
console.log(a.pro);   // 'zhenn'(物件 a 仍存在,未被垃圾回收)

結論:delete 僅切斷「屬性名 → 值」的繫結,值本身若仍被其他引用持有則不會被 GC 回收。

2. 刪除陣列元素:產生「稀疏陣列」,長度不變

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,後續元素前移。

3. 刪除變數:極其詭異的行為

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

底層機制:Property Attributes

每個屬性擁有內部屬性 [[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'

實務建議

  1. 物件屬性刪除:放心使用 delete obj.prop。
  2. 陣列移除元素:永遠使用 splice、filter、pop/shift,不要用 delete。
  3. 釋放記憶體:將變數設為 null / undefined,解除引用讓 GC 回收,而非 delete。
  4. 動態屬性管理:考慮使用 Map / Set,提供 delete(key)、clear()、size 等語義清晰的 API。

總結

delete 專為**物件屬性**設計,對陣列會產生稀疏洞,對變數受作用域與 [[Configurable]] 限制極大。理解其「斷開繫結」本質,避免誤用於陣列或變數釋放。

copyright © 萬盛學電腦網 all rights reserved