【问题标题】:Setting global variable value within functions & if statements在函数和 if 语句中设置全局变量值
【发布时间】:2013-12-09 16:45:54
【问题描述】:

我刚开始接触 JavaScript,但我已经搜索并阅读了有关 js 变量范围的信息,但无法弄清楚。

我希望能够在还包含 if 语句的函数内设置在任何函数之外声明的变量值。但它并没有改变全局变量。示例:

var counter = 0;
goNext();    

function goNext()
{   
    if(counter = 0)
    {
        counter = 3;
    }
}

alert('I now want counter to be 3! How?');

【问题讨论】:

  • 你不是在做比较counter = 0是赋值,用===代替=
  • 确实有效,看来我还有很多阅读工作要做。谢谢!

标签: javascript scope


【解决方案1】:

如果你将 0 分配给 counter

if(counter = 0)

代码需要

if(counter == 0)

if(counter === 0)

使用JSHint 之类的工具可以帮助您找到这些错误。通过将代码粘贴到界面中,它会向您显示警告。当我将您的代码粘贴到它生成的页面中时:

One warning
6   Expected a conditional expression and instead saw an assignment.

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2016-08-17
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多