【发布时间】: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