首页 文章

Javascript while循环,函数作为条件

提问于
浏览
4

我的理解是while条件的内容在条件为真时执行 . 在使用一本很棒的O'Riely书中的一个例子的时候,我遇到了while循环的这个实现......

window.onload = function(){

    var next, previous, rewind; //  globals

    (function(){
        //  Set private variables
        var index = -1;
        var data = ['eeny', 'meeny', 'miney', 'moe'];
        var count = data.length;

        next = function(){
            if (index < count) {
                index ++;
            };
            return data[index];
        };

        previous = function(){
            if (index <= count){
                index --;
            }
            return data[index];
        };

        rewind = function(){
            index = -1;
        };

    })();

    //  console.log results of while loop calling next()...
    var a;
    rewind();
    while(a = next()){
        //  do something here
        console.log(a);
    }


}

我想我想知道为什么,在这段代码中,while循环无法无限地解析为真?在var索引停止递增()之后函数next()没有返回false,是吗?控制台不应该输出eeny,meeny,miney,moe,moe,moe,moe .....等......

我知道这可能是以某种形式提出的,但已经完成了搜索,无法找到解释使用 while (a = function()) {// do something} 以及在一次通过数组后该循环如何停止的问题或答案 .

3 回答

  • 1

    关于为什么 while (a = next()) {/*do something*/} 没有't repeat infinitely, it'关于强制被强制计数 - 在被while循环测试之前,参数被转换为布尔值 . 强制为假的事情包括 0-0undefinednull""NaN ,当然还有 false 本身 .

    分配内容时,它会返回赋值本身的值 . 例如,如果您执行以下操作:

    var a;
    console.log(a = '1234567890abcdefghijklmnopqrstuvwxyz');
    

    它将记录 1234567890abcdefghijklmnopqrstuvwxyz .

    next 执行 index++ 时,会递增 data 数组中元素索引的计数器 . 这意味着每次运行 next() 函数时它都会在数据数组中查找下一个元素 - 如果没有更多元素,它将返回 undefined 并因此结束循环 .

    例如,看到这个:

    var index = 0;
    data = ['a','b','c'];
    data[index]; // 'a'
    index++;
    data[index]; // 'b'
    index++;
    data[index]; // 'c'
    index++;
    data[index]; // undefined - if passed this will coerce to false and end the loop
    Boolean(data[index]); // false
    
  • 3
    if (index < count) {
        index ++;
    };
    

    indexcount - 1 时,这仍然会将 index 更改为 count ,对吗?并且 countdata.length . 那么,它会这样做:

    return data[index];
    

    哪个成了

    return data[data.length];
    

    由于数组的长度超出了数组的范围(它们是从零开始的),因此它将给出 undefined .

    while(a = next()){
    

    会变成

    while(a = undefined){
    

    由于 undefined 是一个假值,因此不会输入循环 .

  • 1

    没有,

    它不会是一个无限循环 . while循环基本上是通过数组并输出它,当它在数组的末尾时它只返回false并退出循环 .

    这就像是;

    foreach(a as nextArray)
    {
    //output
    }
    

    希望这可以帮助 .

相关问题