如何删除/取消设置 javascript 对象的属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6485127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:59:02  来源:igfitidea点击:

How to delete/unset the properties of a javascript object?

javascriptjquery

提问by Click Upvote

Possible Duplicates:
How to unset a Javascript variable?
How to remove a property from a javascript object

可能的重复项:
如何取消设置 Javascript 变量?
如何从javascript对象中删除属性

I'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?

我正在寻找一种方法来删除/取消设置 JS 对象的属性,这样如果我循环执行对象,它们将不再出现for (var i in myObject)。如何才能做到这一点?

回答by RobertPitt

simply use delete, but be aware that you should read fully what the effects are of using this:

只需使用delete,但请注意,您应该完全阅读使用它的效果:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

但如果我像这样使用:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using thisin the outermost scope i.e

但是如果您确实希望删除全局命名空间中的变量,则可以使用它的全局对象,例如window,或this在最外层范围内使用,即

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

http://perfectkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splicewhich is a prototype of the array object.

另一个事实是,在数组上使用 delete 不会删除索引,而只会将值设置为 undefined,这意味着在某些控制结构(例如 for 循环)中,您仍将迭代该实体,当涉及到数组时,您应该使用splicewhich数组对象的原型。

Example Array:

示例数组:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

如果我要这样做:

delete myCars[1];

the resulting array would be:

结果数组将是:

["Saab", undefined, "BMW"]

but using splice like so:

但是像这样使用 splice:

myCars.splice(1,1);

would result in:

会导致:

["Saab", "BMW"]

回答by mplungjan

To blank it:

将其清空:

myObject["myVar"]=null;

To remove it:

要删除它:

delete myObject["myVar"]

as you can see in duplicate answers

正如您在重复答案中看到的那样