简体   繁体   English

我尝试创建一个仅运行一次但始终运行 else 语句的 javascript function

[英]i tried creating a javascript function that only runs once but its always running the else statement

i'm making a basic javascript function that works with onclick but it's always running the else statement which I only want it to run once我正在制作一个基本的 javascript function 与 onclick 一起使用,但它总是运行我只希望它运行一次的 else 语句

here's my script这是我的脚本

function onlyOnce() {
    var runOnce = false;
    console.log("i'm running but i didn't go to the else statement yet")
    if (runOnce) {
        return
    } else {
        console.log("i'm running and i'm in the else statement")
        return runOnce = true;   
    }
}

any help will be appreciated任何帮助将不胜感激

The runOnce variable is defined in the function, and after you leave the function its value is forgotten. runOnce变量在 function 中定义,离开 function 后,它的值被遗忘。 When entering the function, its value will be set to false again.输入 function 时,其值将再次设置为false

One way to solve this, is by bringing the variable outside the function:解决此问题的一种方法是将变量置于 function 之外:

let runOnce = false; // let is usually recommended over var

function onlyOnce() {
    console.log("i'm running but i didn't go to the else statement yet");
    if (runOnce) {  
        return;
    } else {
        console.log("i'm running and i'm in the else statement");
        runOnce = true;
    }
}

You could also make a class such that the function/method is associated with the data:您还可以制作 class 以便函数/方法与数据相关联:

class Something {
    constructor() {
        this.runOnce = false;
    }

    onlyOnce() {
        console.log("i'm running but i didn't go to the else statement yet");
        if (this.runOnce) {
            return;
        } else {
            console.log("i'm running and i'm in the else statement");
            this.runOnce = true;
        }
    }
}

let something = new Something();

something.onlyOnce(); // Prints second statement
something.onlyOnce(); // Prints first statement

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM