JavaScript delete 操作符

delete 操作符用于删除对象的某个属性,如果没有指向这个属性的引用,它最终将会被释放。

1
delete obj['property'];

对于所有结果都返回 true,除非属性是一个不可配置属性,这种情况,在非严格模式下返回 false,在严格模式下则抛出 TypeError

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const originO = {
name: 'Mike',
age: 29,
speak() {
console.log(`I am ${this.name}`);
}
}

Object.defineProperty(originO, 'sex', {
value: '女'
configurable: false
});

console.log(delete originO.sex); // false

'use strict'
console.log(delete originO.sex); // TypeError: Cannot delete property 'sex' of #<Object>
  • 如果要删除的属性不存在,delete 不会有任何作用,但仍返回 true

  • delete 只能删除对象本身上的属性,不会删除原型链上的同名属性(如果有的话)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function originO() {
    this.name = 'originO';
    }

    originO.prototype.name = 'name in prototype';

    let obj = new originO();

    delete obj.name;

    console.log(obj.name); // name in prototype
  • 任何使用 var 声明的属性不能从全局作用域或函数的作用域中删除

    1
    2
    3
    4
    5
    var globalVar = 'XYZ';

    const descriptor = Object.getOwnPropertyDescriptor(window, 'globalVar');

    console.log(descriptor); // { ..., configurable: false, ... }

    可以看到 var 声明的属性不可配置

  • 任何使用 letconst 声明的属性不能从它声明的作用域中被删除

  • delete 删除数组元素

    1
    2
    3
    4
    5
    6
    7
    const arr = [ 1, 2, 3, 4 ];

    delete arr[3];

    console.log(arr); // [ 1, 2, 3, <1 empty item> ]
    console.log(arr.length); // 4
    console.log(arr[3]); // undefined
作者

Y2hlbmdsZWk=

发布于

2019-06-16

更新于

2021-09-01

许可协议