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

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

问题描述

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

我正在寻找一种方法来删除/取消设置 JavaScript 对象的属性,因此如果我循环遍历对象执行 for (var i in myObject),它们将不再出现.这怎么办?

I'm looking for a way to remove/unset the properties of a JavaScript 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?

推荐答案

只需使用 delete,但请注意,您应该充分阅读使用此方法的效果:

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

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

But if you do wish to delete variables in the global namespace, you can use its 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

了解删除

另一个事实是,在数组上使用 delete 不会删除索引,而只会将值设置为 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 arrays 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天全站免登陆