简体   繁体   English

在JavaScript中的函数的循环中设置全局布尔变量的最佳语法

[英]best syntax to set a global boolean variable in a loop in a function in javascript

So this is what I have right now: 这就是我现在所拥有的:

            var flag = false;

            (function() {
                for (var i = 0; i < 5; i += 1) {
                    // some code ....
                    // How can I rewrite the following?
                    if (!flag) {
                        flag = true;
                        // can't break
                    }
                }
            })();

            console.log(flag);

http://jsfiddle.net/btc6wjw9/ http://jsfiddle.net/btc6wjw9/

My goal is set the flag to true when the function executes. 我的目标是在函数执行时将标志设置为true。 What is the more elegant syntax with the same or better performance? 具有相同或更好性能的更优雅的语法是什么?

Thanks! 谢谢!

Update: I have since learned that changing a boolean value is faster than checking it: http://jsfiddle.net/xq7n7bry/ 更新:从那以后,我了解到更改布尔值比检查它更快: http : //jsfiddle.net/xq7n7bry/

        var flag = false;

        (function() {
            for (var i = 0; i < 5; i += 1) {
                // some code ....
            }
            flag = true;
        })();

        console.log(flag);

I don't really understand the point of your question, but if you want to set it to true when the function is called, just set it to true when the function is called. 我不太了解您要问的问题,但是如果要在调用函数时将其设置为true,则只需在调用函数时将其设置为true。

One way to rewrite: 一种重写方式:

if (!flag) {flag = true;}

is

flag = (!flag ? true: flag );

This is not necessarily better, as an assignment will be made at each iteration. 这不一定更好,因为将在每次迭代时进行分配。

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

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