Javascript while loop with conditional function

I understand that the contents of the while loop are executed as long as the condition is true. While working on an example from O'Rileyโ€™s amazing book, I came across this implementation of the while loop ...

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);
    }


}

I think I'm wondering why in this code the while loop does not allow true indefinitely? The function, next () does not return false after the index index stops increasing (++), right? Should the console just print eeny, meeny, myy, moe, moe, moe, moe ..... etc ...

I know that this was probably asked in one form or another, but performed a search and cannot find a question or answer explaining the use while (a = function()) {// do something}and how this loop stops after one passage through the array.

+4
3

, while (a = next()) {/*do something*/} , , - , while. , , 0, -0, undefined, null, "", 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 ++;
};

index - count - 1, index count, ? count - data.length. , :

return data[index];

return data[data.length];

( ), undefined.

while(a = next()){

while(a = undefined){

undefined , .

+1

,

. while , , false .

- :

foreach(a as nextArray)
{
//output
}

, .

+1

All Articles