使用False突破JavaScript'For'循环? [英] Breaking out of JavaScript 'For' Loop using False?

查看:101
本文介绍了使用False突破JavaScript'For'循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是可能的(是吗?)

I didn't know this was possible (is it?)

下面的代码显然记录了值1到5,然后突破了'for'循环,因为返回'false'值。

The below code apparently logs values 1 to 5, then breaks out of the 'for' loop, because the 'false' value is returned.

function x() {
    for (var i = 0; i < 10; i++) {
        console.log(i);
        if (i == 5) return false;
    }
    return true
}

console.log(x());

我的问题是:


  • 返回'false'时for循环如何短路?我看了MDN但是没有任何关于使用'false'来打破for循环的东西。也尝试过看ECMA的规格,但遗憾的是太棒了。

  • How come the for loop short-circuits when 'false' is returned? I looked at MDN but there is nothing there about using 'false' to break out of the for loop. Also tried looking at ECMA specs, but sadly too noob.

为什么函数不会向控制台返回'true',因为'for'循环执行后存在'return true'语句?即使错误以某种方式返回'第一',也不应该'真'返回最后或者也是?

Why doesn't the function return 'true' to the console, as the 'return true' statement exists after the 'for' loop is executed? Even if false somehow returns 'first', shouldn't 'true' return last or also?

推荐答案

return false 不会破坏你的循环,而是将控制权返回到外面。

return false is not breaking your loop but returning control outside back.

function x() {
    for (var i = 0; i < 10; i++) {
        console.log(i);
        if (i == 5) return false;
    }
    return true
}

console.log(x())

输出:

0
1
2
3
4
5
false //here returning false and control also 

其中 break 会破坏你的循环而不是从函数中出来。

Where break will break your loop instead of coming out from function.

function x() {
    for (var i = 0; i < 10; i++) {
        console.log(i);
        if (i == 5) break;
    }
    return true
}

console.log(x())

将输出:

0
1
2
3
4
5 //after this loop is breaking and ouputing true
true 

这篇关于使用False突破JavaScript'For'循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆