问题描述
我学校的老师在教我们,我们必须像这样专门声明函数变量:
函数功能(var1,var2){var var1,var2;console.log(var1);console.log(var2);}东西(完全",酷");
但是我似乎找不到任何与此相关的主题,所以我的问题是,这是否是必需的?只是将 var var1,var2;
留在外面不是很正常吗?
如果是,这是在W3C JavaScript文档中的某个地方说明的吗?
我的意思是无论哪种方式都可以工作,但是如果没有它就可以工作.
我正在谈论的代码: http://pastebin.com/y5B2aznc
谢谢!
在您的特定情况下,所有作为参数传递的变量都是 local 变量,就像您使用 var
.因此,使用 var
重新声明它们是多余的.
但是更好的做法是将参数保留其原始值,并对其进行处理以将结果存储在其他局部变量中.例如:
函数功能(var1,var2){var varAlt1 = var1.toUpperCase(),varAlt2 = var2.toLowerCase();console.log(varAlt1);console.log(varAlt2);}
The teachers at my school are teaching us we have to specifically declare function variables like so:
function something(var1, var2)
{
var var1, var2;
console.log(var1);
console.log(var2);
}
something("Totally", "Cool");
However I can't seem to find any topics about this, so my question is, is this even required? Isn't it perfectly normal and OK to just leave the var var1, var2;
out?
If so, is this stated somewhere in the W3C JavaScript documentation?
I mean it works either way, but if it works without... Cleaner code I'd say :P
Code I'm talking about: http://pastebin.com/y5B2aznc
Thanks!
In your particular case, all the variables passed as arguments are local variables just like the variables you declare with var
. So re-declaring them with var
is redundant.
But a better practice is to leave the arguments with their original values, and do stuff with them storing the results in other local variables. E.g.:
function something(var1, var2)
{
var varAlt1 = var1.toUpperCase(), varAlt2 = var2.toLowerCase();
console.log(varAlt1);
console.log(varAlt2);
}
这篇关于是否需要声明函数变量(使用Javascript)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!