Uri*_*Uri 29 javascript variables var declare
可能重复:
JavaScript变量范围
我有一个用于HTML选择选项的JavaScript函数:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是 - 我可以在两个不同的for循环中声明"var day"两次,这个变量的范围是什么?这是合法的,如果我在同一个函数中声明两次相同的变量会发生什么?(内部循环或外部循环)?例如,如果我用"var"再次声明其中一个变量会发生什么?
如果我在for循环中的变量日之前根本不使用"var",会发生什么?
谢谢,乌里.
PS $ .parse_int是一个jQuery插件,如果没有指定,它会调用基数为10的parseInt.
不,你不应该。using 声明的变量var具有函数作用域,而不是块作用域!
重新声明变量 usingvar可能表明该变量不是循环/块的本地变量。
但是,您可以使用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) // undefinedRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6051 次 |
| 最近记录: |