我进行了以下实验,发现 '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'
最佳答案
My question is: is this the 'proper' way to do it?
这是正确的做法,但是有 two caveats
- 除非该属性不可配置
- 属性(property)继承
例如您不能删除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
关于javascript - 在 typescript 中删除键值对的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48004266/