我写了下面的代码,想要从一个对象中"弹出"一个属性,就像从数组中弹出元素一样。这看起来是那种会让更认真的程序员狠抽我的代码,所以我想知道正确的做法:
// 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
}
我之前应该提到,与真正的“弹出(pop)”不同,我不需要对象按照任何特定顺序出现。我只需要取出一个对象并将其从其父对象中删除。
if (profiles.hasOwnProperty(key) {..
中,并删除= 0
。 - Sean Kinseyfor..in
循环中检索属性的顺序是不确定的。除此之外,你应该使用hasOwnProperty
来确保它不是原型的一部分,并且你只需要使用delete
来从对象中删除属性,无需执行其他操作。 - Jamie Treworgyshift
数组方法,该方法删除(并返回)数组中的第一个元素。pop 删除最后一个元素,因为 push/pop 数组方法作为 FILO。 - jbyrd