我可以在JavaScript中的不同for循环中两次声明同一个变量吗
Can I declare the same variable twice in different for loops in JavaScript?
可能重复:
JavaScript可变范围
我有一个JavaScript功能用于HTML选择选项几天:
// Show and hide days according to the selected year and month.
function show_and_hide_days(fp_form) {
var select_year= $(fp_form).find("select.value_year");
var select_month= $(fp_form).find("select.value_month");
var select_day= $(fp_form).find("select.value_day");
var selected_year= $.parse_int($(select_year).val());
var selected_month= $.parse_int($(select_month).val());
var selected_day= $.parse_int($(select_day).val());
var days_in_month= new Date(selected_year, selected_month, 0).getDate();
// If the number of days in the selected month is less than 28, change it to 31.
if (!(days_in_month >= 28))
{
days_in_month= 31;
}
// If the selected day is bigger than the number of days in the selected month, reduce it to the last day in this month.
if (selected_day > days_in_month)
{
selected_day= days_in_month;
}
// Remove days 29 to 31, then append days 29 to days_in_month.
for (var day= 31; day >= 29; day--)
{
$(select_day).find("option[value='" + day + "']").remove();
}
for (var day= 29; day <= days_in_month; day++)
{
$(select_day).append("<option value='"" + day + "'">" + day + "</option>");
}
// Restore the selected day.
$(select_day).val(selected_day);
}
我的问题是,我可以在两个不同的for循环中声明两次"var-day"吗?这个变量的作用域是什么?它合法吗?如果我在同一个函数中两次声明同一个变量会发生什么?(内侧用于回路或外侧用于回路(?例如,如果我再次用"var"声明其中一个变量,会发生什么?
如果在循环的变量day之前我根本不使用"var",会发生什么?
谢谢,Uri。
p.S.$.parse_int是一个jQuery插件,如果没有指定,它会调用基数为10的parseInt。
在函数中使用var foo
将使foo
适用于该函数。当var
声明被挂起时,这在函数中的何处发生并不重要。
var foo
在同一函数中的其他使用在语法上是合法的,但不会产生任何影响,因为变量已经在该函数的范围内。
由于它没有任何效果,因此有一种学派建议不要使用它(而赞成在函数的最顶部使用一个var
函数来执行所有范围(,以避免暗示它有意义(对于不完全适应JavaScript这一功能的维护人员来说(。JSLint会提醒您注意此用法。
不,你不应该。使用var
声明的变量具有函数作用域,而不是块作用域!
使用var
重新定义变量可能表明该变量是循环/块的本地变量,而不是。
但是,您可以使用let
来声明变量,以确保它是块范围的。
for (let x = 1; x <= 3; x++) {
console.log(x)
}
for (let w = 65, x = String.fromCharCode(w); w <= 67; w++, x = String.fromCharCode(w)){
console.log(x)
}
console.log(typeof x) // undefined
相关文章:
- Meteor Router数据函数被调用两次
- 从MySQL数据库中获取输入数据需要两次页面刷新
- Module.start()已激发两次
- Jquery点击事件必须点击两次
- Append元素在运行两次函数后不显示
- 防止双击执行两次jQuery post请求
- 我必须点击两次才能激活任何按钮操作(离子/角度)
- 单击jQuery会激发两次
- 如何避免在树上走两次
- button.单击两次删除附加操作后不工作
- 由于$compile,Javascript(Angular)嵌套指令加载了两次
- 单击元素两次后执行操作
- AngularJs正在阻止链接被点击两次
- 为什么我的路线处理程序会触发两次
- 为什么要声明两次 jQuery
- 为闭包声明函数两次
- 为什么要两次声明同一个变量的相同值
- 执行上下文两次声明名称
- javascript函数的声明两次
- 我可以在JavaScript中的不同for循环中两次声明同一个变量吗