在TypeScript中,删除键值对的正确方法是什么?

3
我进行了以下实验,发现可以使用“delete”来删除键值对。我的问题是:这是正确的方法吗?
let myMap:{[key:string]:string} = {};

myMap["hello"] = "world";
console.log("hello="+myMap["hello"]); // it prints 'hello=world'

delete myMap["hello"];
console.log("hello="+myMap["hello"]); // it prints 'hello=undefined'

4
delete myMap["hello"]; 是正确的,我没有看到任何问题。 - undefined
1个回答

3
我的问题是:这是做这件事的“正确”方式吗?
这是正确的做法,但有两个注意点
- 除非该属性是不可配置的 - 该属性是被继承的
例如,您无法删除`location`的`href`属性。
delete location.href //returns false since this property cannot be deleted

演示

var b = {
  a: 1,
  b: 2
};
Object.defineProperty(b, "c", {
  enumerable: true,
  configurable: false,
  writable: true,
  value: 3
});
delete b.c;
console.log(b); //all properties intact


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接