← 中文资源

简体中文版本

delete 移除对象属性

delete 摘掉自有属性、in 与 hasOwn 都查不到,赋 undefined 只是值变键仍在;数组上 delete 会留空洞且不改 length,需要缩短用 splice。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

verbose own: false
verbose in: false
value: undefined
after delete: {"timeout":1500}
still own: true
keys: 1
index 1 present: false
length unchanged: 3

实现说明

顶层就这几处状态:options、patch、items。 一个对象字面量承载 retries、timeout、verbose——每个值都就地写死。

使用要点

  • 演示输出是带标签的(verbose own:、verbose in:、value:),每个操作都会留下自己的一行标注。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。 全部导入都来自标准库:present with value undefined。 跨调用保留的状态放在这些顶层绑定里:options、patch、items。

核心语句

const options = { retries: 3, timeout: 1500, verbose: true };
const patch = { debug: false };
const items = ['a', 'b', 'c'];

代码示例

const options = { retries: 3, timeout: 1500, verbose: true };

// delete removes an own property; afterwards both in and hasOwn miss it
delete options.verbose;
console.log('verbose own:', Object.hasOwn(options, 'verbose'));
console.log('verbose in:', 'verbose' in options);

// reading a deleted property yields undefined, but that differs from "present with value undefined"
console.log('value:', options.verbose);
delete options.retries;
console.log('after delete:', JSON.stringify(options));

// assigning undefined does not remove the key: the key stays on the object
const patch = { debug: false };
patch.debug = undefined;
console.log('still own:', Object.hasOwn(patch, 'debug'));
console.log('keys:', Object.keys(patch).length);

// delete on an array leaves holes: the index property disappears while length is unchanged
const items = ['a', 'b', 'c'];
delete items[1];
console.log('index 1 present:', 1 in items);
console.log('length unchanged:', items.length);