Javascript“流行"从对象
我编写了以下代码来从对象中弹出"一个属性,就好像它是一个数组一样.这看起来像是会让我被更严肃的程序员打的那种代码,所以我想知道这样做的正确方法是什么:
I wrote the following code to "pop" a property from an object as if it were an array. This looks like the kind of code that would get me slapped by more serious programmers, so I was wondering what is the proper way to do this:
// 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
}
我应该在上面提到,与真正的流行音乐"不同,我不需要对象以任何特定的顺序出现.我只需要取出一个并将其从其父对象中删除即可.
I should have mentioned above, that unlike a true "pop", I don't need the objects to come out in any particular order. I just need to get one out and remove it from its parent object.
推荐答案
for( key in profiles ){
你真的应该将 key
声明为 var
.
You should really declare key
as a var
.
profiles[key] = 0; // Save over property just in case "delete" actually deletes the property contents instead of just removing it from the object
是不必要的.删除不会触及属性的值(或者对于有setter但没有getter的属性,甚至要求它有一个值).
is unnecessary. Delete doesn't touch the value of the property (or in the case of a property that has a setter but no getter, even require that it have a value).
如果对象在其原型上有任何可枚举的属性,那么这会做一些奇怪的事情.考虑
If the object has any enumerable properties on its prototype, then this will do something odd. Consider
Object.prototype.foo = 42;
function take(obj) {
for (var key in obj) {
// Uncomment below to fix prototype problem.
// if (!Object.hasOwnProperty.call(obj, key)) continue;
var result = obj[key];
// If the property can't be deleted fail with an error.
if (!delete obj[key]) { throw new Error(); }
return result;
}
}
var o = {};
alert(take(o)); // alerts 42
alert(take(o)); // still alerts 42
相关文章