如何删除/取消设置javascript对象的属性? [英] How to delete/unset the properties of a javascript object?

查看:147
本文介绍了如何删除/取消设置javascript对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何取消设置Javascript变量?

如何从javascript对象中删除属性

我正在寻找一种方法来删除/取消设置JS对象的属性,这样如果我循环执行的对象(myObject中的var i),它们将不再出现。怎么办呢?

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?

推荐答案

只需使用删除,但是意识到你应该完全阅读使用它的效果:

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

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

但如果我这样使用:

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 this in the outermost scope i.e

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

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

另一个事实是在数组上使用delete不会删除index但是只将值设置为undefined,这意味着在某些控制结构中,例如for循环,你仍将遍历该实体,当涉及到数组时,你应该使用 splice 是数组对象的原型。

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 splice which is a prototype of the array object.

示例数组:

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

如果我这样做:

delete myCars[1];

结果数组将是:

["Saab", undefined, "BMW"]

但是像这样使用拼接:

myCars.splice(1,1);

会导致:

["Saab", "BMW"]

这篇关于如何删除/取消设置javascript对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆