javascript - 在 typescript 中删除键值对的正确方法是什么

标签 javascript typescript dictionary key-value

我进行了以下实验,发现 '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)继承

例如您不能删除locationhref属性

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/

相关文章:

python - 如何在Python中使用stdout的内容?

swift - 如何通过 NSDate 对 Swift 中的字典进行排序?

java - javascript emberjs 中的 List<Map<String, Object>> 中的 Json 值

javascript - select2 MaximumSelectionSize 删除元素后不起作用

javascript - 单击时将图像预览到另一个 div

TypeScript 导入的常量未定义

javascript - node_modules 中的 typescript 模块是否已经编译

javascript - 使用 HTML/CSS 和 Javascript 的 Domino's Tracker

javascript - Angular 4 模板中的 bool 值

javascript - TypeScript - 仅当有值时才在 POST 上发送可选字段