Ilya Tsuryev提出了一个问题:Dealing with duplicate declaration warning for loop variables,或许与您遇到的问题类似。
回答者user66001Oleg给出了该问题的处理方式:
JavaScript has many constructions which look like well-known constructions in other computer languages. It's dangerous for JavaScript to interpret the construction in another way as most other computer languages.
If somebody who doesn't know JavaScript good enough (the common case by the way) sees the construction like
--- ---- ---- ------ ---- - -- ---- ---- ---- -
or sees declaration of the variable in the block
- --- -- ------ ---- - --- -- -- ---- ---- - -
then most readers will think that block level variables will be defined. JavaScript don't have block level variables. All variables will be interpreted as function level defined.
So I never define variables inside of the code if the code is not just some test code which will be written for 5 min only. The main reason is that I don't want to write code and use language constructions which could be misunderstood.
By the way JSLint finds defining of variables inside of block such bad style that it stop processing of the code analysis. There are no JSLint options which could change this behavior. I find the behavior of JSLint not good, but I agree that declaration of variables inside of for
loop is bad because it will be read by most persons as code with local loop variables, which is incorrect.
If you use
--- ---- ---- ------ ---- - -- ---- ---- ---- - -- ---- ----- ---- ---- --- ---- ---- ------ ---- - -- ------ ---- ---- -
then JavaScript moves all declarations of variables at the beginning of the function for you. So the code will be as
--- - - ---------- - - ---------- -- --------- ----------- ----- ---- -- ------- -- -- --- --- - - ---------- --- ----- ------ ---- - -- ---- ---- ---- - -- ---- ----- ---- ---- --- ----- ------ ---- - -- ------ ---- ---- -
So please think about other readers of the code. Don't use any constructions which could be interpreted in the wrong way.
希望本文对你有帮助,欢迎支持JavaScript中文网
来源:JavaScript中文网 ,转载请注明来源 本文地址:https://www.javascriptcn.com/post/24885