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

I conducted the following experiment, and discovered that 'delete' can be used to remove a ke

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745142386a4613489.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信