【问题标题】:What is the proper way to remove a key-value pair in typescript在打字稿中删除键值对的正确方法是什么
【发布时间】:2017-12-28 16:59:16
【问题描述】:

我进行了以下实验,发现可以使用“删除”来删除键值对。我的问题是:这是“正确”的做法吗?

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'

【问题讨论】:

  • delete myMap["hello"]; 是正确的,我看不出有什么问题。

标签: javascript typescript dictionary key-value


【解决方案1】:

我的问题是:这是“正确”的做法吗?

这是正确的做法,但是有two caveats

  • 除非属性不可配置
  • 属性被继承

例如你不能删除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

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多