简体   繁体   中英

While-Loop Logic JavaScript

I am trying to understand the logic of the statement block in the while loop. I understand the expression of the while loop, which is as long "idx" is not equal to -1. Push idx value into indices array.

The statement that I have trouble understanding is " idx = array.indexOf(element, idx + 1); "

Is idx increasing after every iteration since it is being increased by 1?

I would appreciate it if someone would help me understand the logic. I am quite confused because idx is assign to array.indexOf(element);

The following code snippet is from 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's answer is close.

The point of this

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

is to intialize the variable idx's to 0 . Because the index of the array for 'a' is 0

Then the loop begins

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
}

So basically, If this were the array. var array = ['1', 'a', 'a', 'a', '1', 'm'];

var idx = array.indexOf(element) , would return '1' FIRST!

so idx != -1 and the pushing starts!

Edit: clarify the exit of the while loop.

As soon as the while loop hits the 4th position of this new array indexOf(element, 4); it would then return -1 exiting the while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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