【发布时间】:2011-10-01 15:02:25
【问题描述】:
我编写了以下代码来从对象中“弹出”一个属性,就好像它是一个数组一样。这看起来像是会让我被更严肃的程序员打的那种代码,所以我想知道这样做的正确方法是什么:
// wrong way to pop:
for( key in profiles ){
var profile = profiles[key]; // get first property
profiles[key] = 0; // Save over property just in case "delete" actually deletes the property contents instead of just removing it from the object
delete profiles[key]; // remove the property from the object
break; // "break" because this is a loop
}
我应该在上面提到,与真正的“流行音乐”不同,我不需要对象以任何特定的顺序出现。我只需要取出一个并将其从其父对象中删除即可。
【问题讨论】:
-
用
if (profiles.hasOwnProperty(key) {..包裹身体并松开= 0 -
你到底想做什么?删除添加到对象的第一个属性?这不一定有效,因为不能保证在
for..in循环中检索属性的顺序。除此之外,您应该使用hasOwnProperty来确保它不是原型的一部分,并且您不需要执行除delete之外的任何操作来从对象中删除属性。
标签: javascript object iterator