可能重复:
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