Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

JS do ... while

It seems to me that i misunderstand the behavior of the do ... while loop in JS. Let's say we have a 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);

Which is intended to roll out random item from array a if that item is not 4. But if we roll several times we'll see that it doesn't actually prevent 4 from getting to array b. Why? I thought that it would work like this:

  1. Roll random item from array a, store it to c and push c to b;
  2. Check if (c===4) is true;
  3. If it is — go to paragraph 1;
  4. If it's not — log b to console.

Where am I mistaking and why does this code work in such a way? What are others way to 'ban' some item from array from being rolled randomly (except filtering the array) if this approach can't help me?

Answer*

Draft saved
Draft discarded
Cancel

lang-js

AltStyle によって変換されたページ (->オリジナル) /