当`delete` 在JavaScript 中非常有用时,有哪些用例? [英] What are some use-cases of when `delete` has been very useful in JavaScript?

查看:49
本文介绍了当`delete` 在JavaScript 中非常有用时,有哪些用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在这里有一些问题以更抽象的方式讨论删除,但我正在寻找实际示例,说明何时可以使用 delete,而不是将属性设置为null 或未定义.

We have some questions here that discuss delete in a more abstracted way, but I'm looking for practical examples of when use of delete could be used, versus doing something such as setting the property to null or undefined.

删除运算符删除对象的属性.

在某处遇到挑战的情况是什么,delete 是最佳解决方案,而不是其他方法?

What's a case of a challenge faced somewhere, that delete was the best solution, versus something else?

推荐答案

Object.defineProperty(Object.prototype, "Incognito", {
  get: function() { return 42; },
  set: function() { },
  configurable: true
});

console.log(({}).Incognito); // 42
({}).Incognito = null;
console.log(({}).Incognito); // 42

// I DO NOT WANT INCOGNITO
delete Object.prototype.Incognito
console.log(({}).Incognito); // undefined

如果您想删除任何具有空 setter 的属性(因为有人认为 是个好主意),则需要删除它.

Any property which has an empty setter (Because someone thought that was a good idea) needs to be deleted if you want to get rid of it.

var hash = {
  "FALSE": undefined,
  "TRUE": null
}

console.log("TRUE" in hash); // true
console.log("FALSE" in hash); // true
delete hash.FALSE;
console.log("FALSE" in hash); // false

in 运算符为任何存在的属性返回 true,无论其值如何.如果您希望它返回 false,您需要 delete 属性.

The in operator returns true for any property that exist no matter it's value. If you want it to return false you need to delete the property.

在这两种情况下,将它设置为 nullundefined 什么都不做(因为它要么有一个什么都不做的 setter,要么就是 in代码>操作符有效)

In both these cases setting it to null or undefined does nothing (Because it either has a setter that does nothing, or that's how the in operator works)

这篇关于当`delete` 在JavaScript 中非常有用时,有哪些用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆