【问题标题】:Javascript while loop with function as conditional以函数为条件的 Javascript while 循环
【发布时间】:2013-11-29 14:41:59
【问题描述】:

我的理解是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 循环没有无限地解析为 true?在 var index 停止递增 (++) 后,函数 next() 不会返回 false,是吗?控制台不应该只是输出eeny,meeny,miney,moe,moe,moe,moe.....等......

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

【问题讨论】:

    标签: javascript function loops while-loop


    【解决方案1】:

    关于while (a = next()) {/*do something*/} 不会无限重复的原因,它是关于被强制 为 false 的 - 参数在被 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
    

    【讨论】:

      【解决方案2】:
      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是一个假值,所以不会进入循环。

      【讨论】:

        【解决方案3】:

        不,

        这不会是一个无限循环。 while 循环基本上是遍历数组并输出它,当它位于数组的末尾时,它只返回 false 并退出循环。

        这有点像;

        foreach(a as nextArray)
        {
        //output
        }
        

        希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-13
          • 2014-04-30
          • 2018-09-22
          • 2016-04-08
          • 2018-10-02
          • 2021-01-04
          • 2019-10-26
          • 2023-04-01
          相关资源
          最近更新 更多