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:
a, store it to c and push c to b;(c===4) is true;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?
Do while runs and THEN checks. So it will get a random number from A, store that in C and push that to B, and THEN if C is 4, it will do another loop.
So if C is 4, it will still push it to B, it just won't continue after that.
You could 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're trying to do? Continuously push a random item from A into B unless you get the result 4, in which case, quit and go to console.log?
As explained by the commenters, you're still pushing 4. You can avoid it by make it very explicit what happens 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With