我可以在JavaScript的不同for循环中声明两次相同的变量吗?

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.

Que*_*tin 27

var foo函数中的任何使用都将适用foo于该函数.由于var声明被提升,因此在函数中的位置并不重要.

var foo在同一函数中的其他用法在语法上是合法的,但由于变量已经作用于该函数,因此无效.

由于它没有任何效果,因此有一种思想建议反对它(并且支持在var函数的最顶层使用单个函数来执行所有范围)以避免暗示它具有重要性(对于维护者而言)对JavaScript的这个功能并不完全满意.JSLint会提醒您这种用法.


pha*_*t0m 5

不,你不应该。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) // undefined
Run Code Online (Sandbox Code Playgroud)