Here i have an array with undefined number of elements. I tried to print random element of this array and cut it. Here my code.
function rand(min, max){
return (Math.floor(Math.random() * (max - min + 1)) + min).toFixed(0);
}
$('#do').click(function(){
var count = chamarr.length;
var num = 0;
if (count == 1) {
$('#output').html('Nothing can found');
} else {
num = rand(1,chamarr.length);
$('#output').html(chamarr[num]);
chamarr.splice(num,1);
}
});
When I logged an array is cutted, I saw that always ok, but sometimes element is not cut!
My guess is that the problem is with your
randnummethod:I believe this will give you a value in the range
[min, max]– inclusive at both ends. (Well, actually, it will give you a string version of that value astoFixedreturns a string, but when you use it later it’ll get coerced back into a number.)Now you’re calling it like this:
So if the array is 6 elements long, you’ll get a value in the range
[1, 6]. But then you’ll try to takechamarr[num]– and the range of valid indexes is[0, 5]as arrays are 0-based. If you try to take element 6, that will give youundefined– but then splicing at element 6 won’t do anything.I would change your
randmethod to be exclusive at the upper bound, like this:and then call it like this:
That will give you a value in the right range for both indexing and splicing.
EDIT: In response to comments etc:
It’s probably worth removing the
toFixed(0)part of therandfunction; you don’t really want a string, after all. This isn’t really part of what was wrong before, but it’s generally cleaner:You might also want a version of the function that makes the
0lower bound implicitMath.floor()/Math.random()calls instead of having a separate function, but personally I’d want to keep them well away from the “logic” code which just wants to get a random number and use it.forloops with inclusive lower bounds and exclusive lower bounds, etc.