javascript - 在循环中,是重新定义全局变量更好,还是一遍又一遍地重新声明和重新定义局部变量更好,还是没有区别?

标签 javascript loops global-variables variable-declaration

例如:

for(var i = 1; i<100; i++){
  var inc = 1/i*PI;
  //and so forth
}

在任何方面都比

更好或更差
var inc = 1/1*PI;
for(var i = 1; i<100; i++){
  inc = 1/i*PI;
}

当然,第一个更容易输入,但是当不断地重新声明相同的变量而不是向全局变量重新分配值时,它可能会降低程序的速度/性能(即使是一点点)。谢谢。

最佳答案

因为 var hoisting ,两者绝对没有区别。而且根据文档,这没有什么区别:

For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain.

现在,如果您使用 let如果不使用 var,情况就会有所不同。我认为根本不会有任何性能差异,但肯定会存在语义差异。 let 的文档详细介绍了这些差异。

关于javascript - 在循环中,是重新定义全局变量更好,还是一遍又一遍地重新声明和重新定义局部变量更好,还是没有区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41785498/

相关文章:

loops - 迭代映射和减少操作

java - 当循环重新开始时,循环内的局部变量会被销毁吗?

javascript - Youtube如何实现此列表控件?

PHP : How to merge child arrays?

Python 全局关键字与 Pylint W0603

python - 通过 C API 在 Python 模块中定义全局变量

Javascript - 使局部变量像全局变量一样

JavaScript 异步/等待 : await is a reserved word

javascript - GraphQL 参数如何与字段关联?

javascript - onChange 事件不会触发 React 的输入字段