Javascript“流行"从对象

Javascript quot;popquot; from object(Javascript“流行从对象)
本文介绍了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

这篇关于Javascript“流行"从对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Should I use window.navigate or document.location in JavaScript?(我应该在 JavaScript 中使用 window.navigate 还是 document.location?)
Power BI - Get data from post request(Power BI - 从发布请求中获取数据)
Embed a Power BI report in React JS to get report instance(在 React JS 中嵌入 Power BI 报表以获取报表实例)
Create Report in Embed View via PowerBI API(通过 PowerBI API 在嵌入视图中创建报表)
Interactive Dialog Box in PowerBI(PowerBI 中的交互式对话框)
Print/Generate PDF of embedded power bi report(打印/生成嵌入式 power bi 报告的 PDF)