Javascript“pop”来自对象 [英] Javascript "pop" from object

查看:129
本文介绍了Javascript“pop”来自对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码,以便从对象中弹出一个属性,就像它是一个数组一样。这看起来像是会让我被更严肃的程序员打耳光的那种代码,所以我想知道这样做的正确方法是什么:

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

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 pop(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(pop(o));  // alerts 42
alert(pop(o));  // still alerts 42

这篇关于Javascript“pop”来自对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆