只运行一次javascript块

时间:2018-02-09 12:38:54

标签: javascript

我有这个javascript函数,我想以12的倍数警告12,24,36 ...等等。我附上了以下代码

<script type="text/javascript">
    function test() {
        var global1=12;
        var final;
        var check;
        if(check) {
            final=global1;
            check=true;
        } else {
            final=final+12;
        }
        alert(final);
    }

    test();
    test();
    test();
</script>

3 个答案:

答案 0 :(得分:1)

您可以对值和最终值进行闭包,并返回一个函数来更新值,直到达到最终值。

var test = function (final) {
        var value = 0;
        return function () {
            if (value < final) {
                value += 12;
            }
            console.log(value);
        };
    }(36); // call with final value

test();
test();
test();
test();

答案 1 :(得分:0)

除了我的评论,这里有一个更简单的功能版本:

&#13;
&#13;
var count = 0;

function twelve(){
  count += 12;
  console.log(count);
}

twelve();
twelve();
twelve();
&#13;
&#13;
&#13;

答案 2 :(得分:0)

全局声明变量而不是功能块。 例如:

var global1 = 12;
var final;
var check = true;

function test()
{
    if(check) {
        final = global1;
        check = false;
    } else {
        final = final + 12;
    }
    alert(final);
}

test();
test();
test();