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:

  1. roll random item array a, store c , push c b;
  2. check if (c===4) true;
  3. if — go paragraph 1;
  4. 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

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -