我编写了以下代码来从对象中弹出"一个属性,就好像它是一个数组一样.这看起来像是会让我被更严肃的程序员打的那种代码,所以我想知道这样做的正确方法是什么:
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模板网!
discord.js v12:我如何等待 DM 频道中的消息?discord.js v12: How do I await for messages in a DM channel?(discord.js v12:我如何等待 DM 频道中的消息?)
如何让我的机器人提及发出该机器人命令的人how to make my bot mention the person who gave that bot command(如何让我的机器人提及发出该机器人命令的人)
如何修复必须使用导入来加载 ES 模块 discord.jsHow to fix Must use import to load ES Module discord.js(如何修复必须使用导入来加载 ES 模块 discord.js)
如何列出来自特定服务器的所有成员?How to list all members from a specific server?(如何列出来自特定服务器的所有成员?)
Discord bot:修复“找不到 FFMPEG"Discord bot: Fix ‘FFMPEG not found’(Discord bot:修复“找不到 FFMPEG)
使用 discord.js 加入 discord 服务器时的欢迎消息Welcome message when joining discord Server using discord.js(使用 discord.js 加入 discord 服务器时的欢迎消息)