gpt4 book ai didi

带有条件函数的Javascript while循环

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:35:25 24 4
gpt4 key购买 nike

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

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

最佳答案

关于为什么 while (a = next()) {/*do something* 不会无限重复,重要的是被强制为 false -在 while 循环测试之前,参数被转换为 bool 值。强制为false的东西包括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

关于带有条件函数的Javascript while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20014061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com