简体   繁体   English

拼接内部 Object.keys(obj).forEach(function(index)

[英]splice inside Object.keys(obj).forEach(function(index)

Is it ok to do something like this in node.js:可以在 node.js 中做这样的事情吗:

Object.keys(obj).forEach(function(index) { 
   if (index == 'sth')
      obj.splice(obj.indexOf(index), 1);
}

I wonder if this splice will do the expected thing if the script is executed by many clients writing in/out into the obj object.我想知道如果脚本由许多写入/写入 obj 对象的客户端执行,这个拼接是否会做预期的事情。

obj is indeed an object and index can be an alphanumeric value. obj 确实是一个对象,索引可以是一个字母数字值。 So, splice does not work in objects, instead should use delete.因此, splice 在对象中不起作用,而应使用 delete。 Same question then,is it ok to use delete inside a foreach of an object?那么同样的问题,可以在对象的 foreach 中使用 delete 吗?

You're not doing forEach on obj .你不是在obj上做forEach (You can't, forEach is only defined for array-like things.) You're doing forEach on an array created by finding all of the own enumerable properties of obj via Object.keys . (你不能, forEach只为类似数组的东西定义。)你正在通过通过Object.keys查找obj所有自己的可枚举属性创建的数组上执行forEach

Let's look at the code with the change you describe above and the syntax error corrected:让我们看看上面描述的更改并更正语法错误的代码:

Object.keys(obj).forEach(function(key) { 
   if (key == 'sth')
      delete obj[key];
});

Sure, you can delete properties from obj within the forEach callback on the array from Object.keys .当然,您可以从Object.keys数组的forEach回调中删除obj中的属性。 It has no effect at all on the array that you're looping over.它对您循环的数组没有任何影响。


Side note: When you use delete on an object, on V8 (the JavaScript engine NodeJS uses) and some others it markedly reduces the performance of looking up properties of that object later, because it goes from the optimized version to a "dictionary mode" version.旁注:当你对一个对象、V8(NodeJS 使用的 JavaScript 引擎)和其他一些对象使用delete时,它会显着降低稍后查找该对象属性的性能,因为它从优化版本变为“字典模式”版本。 Of course, this only matters if you've identified the object as the source of a performance problem;当然,这仅在您将对象确定为性能问题的根源时才重要; until then, delete away... :-)在那之前,删除掉... :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM