首页 > 解决方案 > 是否可以从 JavaScript 中的 if 语句的主体将新字符串附加到 if 语句之外的变量?

问题描述

我试图用下面的代码完成的是在执行 if 语句时将单词“you”添加到变量“holis”中。

仅当满足 if 语句和随后的 console.log 时,我得到的结果是“嘿你”。

但是,当再次执行 SetTimeout 时,我会回到原来的“holis”变量(没有“you”)

JavaScript中有没有办法将字符串永久附加到字符串?我已经尝试过连接。

var holis = "hey"

    if (this.txt2.substr(this.txt2.length - 3) === "...") {

        this.txtElement2.innerHTML = `<span class="intro-text">${this.txt2}</span>`;

        holis += " you"

        console.log(holis)

    } else {
        this.txtElement2.innerHTML = `<span class="intro-text">${this.txt2}</span>`;
    }

    console.log(holis)

    setTimeout(() => this.type2(), this.wait2);

 }

谢谢!

标签: javascript

解决方案


推荐阅读