Should I use var in the for in construct?

一个人想着一个人 提交于 2019-12-02 01:29:08

You should always use var, if you want the value to be local.

Using the keyword object for a variable, is not recommended, you might run into undefined behavior across browsers.

Also you should generally avoid applying anything that is suppose to be local to the global scope.

This is bad:

for (varName in object) {
    alert(varName + " is" + object[varName])
}

This is correct:

for (var varName in object) {
    alert(varName + " is" + object[varName])
}

If you need to access this value in the global scope, you are probably doing it wrong. Also having this in the global scope is useless, as it will only be the last value, that will exist in the varName.

You should always use var, otherwise you are accessing a global variable (and there's a risk you are overwriting someone's else variable)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!