【问题标题】:Function isn't working with a gobal variable. Should it be expected?函数不适用于全局变量。应该期待吗?
【发布时间】:2022-01-20 12:07:48
【问题描述】:

正如标题所说,如果它是全局的,我不能在我的函数上使用变量“countDash”,只能在本地使用。应该是这样吗?

我错过了什么?提前致谢。

//count
let countEl = document.getElementById("count-el");
let saveEl = document.getElementById("save-el");
let count = 0;

//message to user
let username = "Mr. Unknown";
let message = "You have three new notifications";
let messageToUser = `${message}, ${username}!`;

//welcome message
let welcomeEl = document.getElementById("welcome-el");
let name = "Eduardo";
let greeting = "Welcome back";
welcomeEl.innerHTML = `${greeting}, ${name}!`;

function increment() {
    count += 1;
    countEl.innerHTML = count;
}

// let countDash = ` ${count} -`; //does not work
function save() {
    let countDash = ` ${count} -`; //it only works if I have it here localy
    saveEl.innerHTML += countDash;
}

【问题讨论】:

  • “不起作用”究竟是什么意思?有什么事吗?是否报告错误?
  • 您应该添加更多详细信息

标签: javascript function variables global-variables local-variables


【解决方案1】:

当您在全局范围内声明 CountDash 时,代码仅运行一次,因此 CountDash 使用值“0 -”进行初始化。因此,即使您在增量函数中更新计数,countDash 也不会更新。如果您出于某种原因想将 countDash 保留为全局变量(尽管我们应该尽可能减少全局变量的使用),您可以在增量函数中更新 count 后更新它:)

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 1970-01-01
    • 2013-02-19
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 2014-04-04
    相关资源
    最近更新 更多