繁体   English   中英

循环逻辑JavaScript

[英]While-Loop Logic JavaScript

我试图理解while循环中语句块的逻辑。 我了解while循环的表达式,只要“ idx”不等于-1。 将idx值推入索引数组。

我很难理解的语句是“ idx = array.indexOf(element,idx + 1);”

idx是否在每次迭代后都增加,因为它增加了1?

如果有人能帮助我理解逻辑,我将不胜感激。 我很困惑,因为idx被分配给array.indexOf(element);

以下代码段来自Mozilla Developers

 var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.indexOf(element); while (idx != -1) { indices.push(idx); idx = array.indexOf(element, idx + 1); } console.log(indices); // [0, 2, 4] 

@dvenkatsagar的答案很接近。

这一点

var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var idx = array.indexOf(element);

是将变量idx初始化为0 因为数组'a'的索引为0

然后循环开始

while (idx != -1) { // This first tests to make sure there is at least one position for a
  indices.push(idx); // pushes that first index position 0 into the array
  idx = array.indexOf(element, idx + 1); //starts the search again at indexOf position 1... because it was just at 0 and found the 'a' element
}

所以基本上,如果这是数组。 var array = ['1', 'a', 'a', 'a', '1', 'm'];

var idx = array.indexOf(element) ,将首先返回“ 1”!

所以idx!= -1并开始推送!

编辑:澄清while循环的退出。

当while循环到达此新数组的第4个位置时indexOf(element, 4); 然后它将返回-1,退出while循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM