JS do ... while

It seems to me that I am misunderstanding the behavior of do ... while loop in JS. Let's say we have code like:

var a = [1,2,3,4,5];
var b = [];
var c;
do {c = a[Math.floor(Math.random()*a.length)];
    b.push(c);}
while(c===4);
console.log(b);

      

Designed to expand a random element from an array a

if this element is not 4

. But if we roll back several times, we will see that it does not actually prevent the 4

transition to the array b

. What for? I thought it would work like this:

  • Load a random element from the array a

    , save it before c

    and click c

    on b

    ;
  • Check that (c===4)

    true

    ;
  • If it is - go to step 1;
  • If it is not - log b

    to console.

Where am I going wrong and why does this code work this way? What are other ways to "disallow" any element from the array to be accidentally checked (other than filtering the array) if this approach cannot help me?

+3


source to share


3 answers


It is carried out during the run and is THEN checked. So it will get a random number from A, store it in C and push B, and then if C is 4, it will loop again.

So if C is 4, it will still push it to B, after that it just won't continue.

You can do it like this:



var a = [1,2,3,4,5];
var b = [];
var c = a[Math.floor(Math.random()*a.length)];
while (c !== 4) {
  b.push(c);
  c = a[Math.floor(Math.random()*a.length)];
}
console.log(b);

      

I think this is what you are trying to do? Continuously push a random item from A to B unless you get a result of 4, in which case exit and go to console.log?

+1


source


As the commenters explained, you click anyway 4

. You can avoid this by making it very clear what will happen when.



var a = [1,2,3,4,5];
var b = [];
var c;
var keep_going = true;
while (keep_going) {
    c = a[Math.floor(Math.random()*a.length)];
    if (c === 4) {
        keep_going = false;
    } else {
        b.push(c);
    }
}
console.log(b);

      

+1


source


So, as your code is written, you are not "bannning" 4 from append to b

. The code you wrote will add the value from a

to b

, and if the added value is 4, keep adding the values ​​from a

to b

until the last added value is 4. So you get results like:

b == [1];
b == [5];
b == [4,1];
b == [4,4,4,4,4,4,3];

      

Since it do-while

is a looping mechanism, I am assuming that you want to keep adding value from a

to b

until you find one that is not 4. This will

var a = [1,2,3,4,5],
    b = [],
    c;
do {
    c = a[Math.floor(Math.random()*a.length)];
    if(c!==4) { b.push(c); }
} while(c===4);
console.log(b);

      

This will result in the following values ​​for b

b == [1];
b == [2];
b == [3];
b == [5];

      

0


source







All Articles