2012-12-23 111 views
24

可能重复:
JavaScript Variable Scope我可以在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); 
} 

我的问题是 - 我可以宣布 “VAR日”在两个不同的循环中两次,这个变量的范围是什么?这是合法的吗?如果我在同一个函数中声明两次相同的变量会发生什么? (内部for循环或外部for循环)?例如,如果我用“var”再次声明其中一个变量会发生什么?

如果我在for循环的变量日前没有使用“var”,会发生什么?

谢谢, Uri。

P.S. $ .parse_int是一个jQuery插件,如果未指定,它将以10为基数调用parseInt。

+2

你可以自己测试。试试看看会发生什么! –

回答

25

任何在功能中使用var foo都会将foo范围限定为该功能。这个功能在哪里发生并不重要,因为var声明被挂起。

var foo在同一函数中的其他用途在语法上是合法的,但不会起作用,因为该变量已被限制为该函数。

由于它没有任何作用,所以有一个思想学派建议反对它(并且赞成在函数的最顶端使用单个函数来执行所有范围界定),以避免暗示对它(对于不完全适应JavaScript这一特性的维护者)。 JSLint会提醒你这个用法。

4

不,你不应该。 JavaScript具有功能范围,而不是范围范围!

我在说,不应该这样做,因为它可能表明该变量对于循环/块是本地的,当它不是。

相关问题