問題描述
我編寫了以下代碼來從對象中彈出"一個屬性,就好像它是一個數組一樣.這看起來像是會讓我被更嚴肅的程序員打的那種代碼,所以我想知道這樣做的正確方法是什么:
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
這篇關于Javascript“流行"從對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!