[英]Best usage of var at loops
I often end up doing something like this: 我经常最终会做这样的事情:
var IDs = getArrayOfIDs();
IDs.forEach(function(ID){
var object = myObjects[ID];
// do stuff with object
});
As far as I understand, this creates a private variable called object
for every ID
inside my IDs
array. 据我了解,这会为我的
IDs
数组中的每个ID
创建一个称为object
的私有变量。 Fine. 精细。
But I could also do it this way: 但是我也可以这样:
var IDs = Obj.getArray();
var object;
IDs.forEach(function(ID){
object = myObjects[ID];
// do stuff with object
});
Now I am using a global variable inside my parent function. 现在,我在父函数中使用了全局变量。 And with that I don't need to create a new variable for every ID.
这样, 我不需要为每个ID创建一个新变量。
Is this an actual advantage (let's say I got a very big array) or a bad idea in general? 这是一个实际的优势(比如说我有很多优势)还是一个坏主意?
Do what is most meaningful and doesn't have a possibility of screwing your code over with problematic variable scopes. 做最有意义的事情,并且不可能将代码与问题变量范围搞混。 If
object
is only used inside the callback, then create it inside the callback and limit its scope to it. 如果
object
仅在回调内部使用,则在回调内部创建object
并将其范围限制为它。 If you don't need it outside, don't make it available outside. 如果您在外面不需要它,请不要在外面使用它。 By your logic you'd be working with all global variables, and that certainly isn't a good idea.
按照您的逻辑,您将使用所有全局变量,但这当然不是一个好主意。
And with that: I don't need to create a new variable for every ID.
这样:我不需要为每个ID创建一个新变量。
And you aren't actually creating "a new variable". 而且您实际上并没有创建“新变量”。 You only have
var object
once in your code; 您的代码中只有一次
var object
; that's one variable . 那是一个变量 。 This variable may be recreated/overwritten a number of times, but it's one logical variable.
可以多次重新创建/覆盖此变量,但这是一个逻辑变量。 Let the Javascript engine worry about performance optimization unless you have a very clear indicator that something is an actual performance problem.
让Javascript引擎担心性能优化, 除非您有非常清楚的指示,表明某些问题是实际的性能问题。
What are you optimizing for? 您正在优化什么?
The downsides are: 缺点是:
Also, depending on what the object entry contains, you might just be creating a reference to the variable. 另外,根据对象条目包含的内容,您可能只是创建对变量的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.