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:
- Roll random item from array
a, store it tocand pushctob; - Check if
(c===4)istrue; - If it is — go to paragraph 1;
- If it's not — log
bto 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?
3 Answers 3
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?
Comments
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);
Comments
So the way your code is written, you are not "bannning" 4 from being added to b. The code you have written will add a value from a to b and, if the value added equals 4, continue to add values from a to b until the last value added does not equal 4. So you will get results like:
b == [1];
b == [5];
b == [4,1];
b == [4,4,4,4,4,4,3];
Since do-while is a looping mechanism, I'm assuming you want to keep trying to add a value from a to b until you find one that is not 4. That would be
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 produce the following values for b
b == [1];
b == [2];
b == [3];
b == [5];
bare you expecting?