标签云

微信群

扫码加入我们

WeChat QR Code

Possible Duplicates:How to unset a Javascript variable?How to remove a property from a javascript objectI'm looking for a way to remove/unset the properties of a JS object so they'll no longer come up if I loop through the object doing for (var i in myObject). How can this be done?


Did you make any attempt to research for yourself? When I googled "javascript delete object properties", this was the first result:How to remove a property from a javascript object

2019年05月22日12分14秒

How about respecting the rules of the site? From the faq: "Please look around to see if your question has already been asked (and maybe even answered!) before you ask."

2019年05月22日12分14秒

That's not a rule.

2019年05月22日12分14秒

ClickUpvote: It is!

2019年05月22日12分14秒

tl;dr can we delete windows["myVar"] or not?

2019年05月22日12分14秒

the simple answer is yes you can, you cna do: var x = 1; and then delete window.x;

2019年05月22日12分14秒

"you can use it's global object such as window, or using this in the outermost scope i.e" and "the simple answer is yes you can, you cna do: var x = 1; and then delete window.x; " No, you can't. If a global is declared with var, it cannot be deleted, not even with delete window.varname. Example: jsbin.com/ojuyig Whereas if you didn't use var (if you just create the global by assigning to it, e.g., window.varname = 42), you can delete that. But var creates an environment binding on the global object (window, in browsers), and those cannot be deleted.

2019年05月22日12分14秒

RobertPitt, delete has no effect on varibles created by "var", so your 3rd example is not correct. see [developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

2019年05月22日12分14秒

A "bit" late, but in case somebody else finds this answer: I found RobertPitt's statement that "delete" on an array element doesn't remove the index to be wrong. delete does remove the index -- it doesn't show up in "for-in" nor in "index-in-array" anymore. The array has a "hole" at that index afterwards. Actually, splice is the one that doesn't delete the index because it will re-number subsequent elements to fill the hole (unless you're splicing away the last elements of the array).

2019年05月22日12分14秒

myObject["myVar"]=null;, will not remove the index, it just set's the value to null, it still exists!

2019年05月22日12分14秒

Hence the delete

2019年05月22日12分14秒