最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the proper way to remove a key-value pair in typescript - Stack Overflow

programmeradmin2浏览0评论

I conducted the following experiment, and discovered that 'delete' can be used to remove a key-value pair. My question is: is this the 'proper' way to do it?

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'

I conducted the following experiment, and discovered that 'delete' can be used to remove a key-value pair. My question is: is this the 'proper' way to do it?

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'
Share Improve this question asked Dec 28, 2017 at 8:41 ExKExK 1112 silver badges10 bronze badges 1
  • 4 delete myMap["hello"]; is correct, I don't see any problem. – gurvinder372 Commented Dec 28, 2017 at 8:43
Add a ment  | 

1 Answer 1

Reset to default 3

My question is: is this the 'proper' way to do it?

This is the accurate way of doing it, but there are two caveats

  • unless the property is non-configurable
  • property is inherited

For example you cannot delete href property of location

delete location.href //returns false since this property cannot be deleted

Demo

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

发布评论

评论列表(0)

  1. 暂无评论