【问题标题】:Can anyone help me with this weird behaviour of var in javascript?任何人都可以帮助我解决 var 在 javascript 中的这种奇怪行为吗?
【发布时间】:2021-10-22 14:05:21
【问题描述】:

fruit 变量如何在 if 块中被覆盖,而 color 变量在功能块中却没有被覆盖?

var fruit = "apple";

if(fruit){
    var fruit = "mango";
    console.log(fruit); // mango
}

console.log(fruit); // mango

var color = "blue";

function displayColor(){
    var color = "red";
    console.log(color);
}

displayColor(); // red

console.log(color);  // blue

【问题讨论】:

标签: javascript


【解决方案1】:

不同之处在于该函数创建了一个本地范围。因此,它在函数范围内创建一个变量,并在函数完成时将其丢弃,保持 GLOBAL 颜色变量不变。

If 语句不构成范围,因此您只需在全局范围内重新定义 fruit 变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2014-04-03
    相关资源
    最近更新 更多