javascript - JS do ... while -
it seems me misunderstand behavior of ... while loop in js. let's have code like:
var = [1,2,3,4,5]; var b = []; var c; {c = a[math.floor(math.random()*a.length)]; b.push(c);} while(c===4); console.log(b);
which intended roll out random item array a
if item not 4
. if roll several times we'll see doesn't prevent 4
getting array b
. why? thought work this:
- roll random item array
a
, storec
, pushc
b
; - check if
(c===4)
true
; - if — go paragraph 1;
- if it's not — log
b
console.
where mistaking , why code work in such way? others way 'ban' item array being rolled randomly (except filtering array) if approach can't me?
do while runs , checks. random number a, store in c , push b, , if c 4, loop.
so if c 4, still push b, won't continue after that.
you this:
var = [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 you're trying do? continuously push random item b unless result 4, in case, quit , go console.log?
Comments
Post a Comment