javascript - Splice only working part of the time -


here have array undefined number of elements. tried print random element of array , cut it. here 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 logged array cutted, saw ok, element not cut!

my guess problem randnum method:

function rand(min, max){ return (math.floor(math.random() * (max - min + 1)) + min).tofixed(0); } 

i believe give value in range [min, max] - inclusive @ both ends. (well, actually, give string version of value tofixed returns string, when use later it'll coerced number.)

now you're calling this:

num = rand(1,chamarr.length); 

so if array 6 elements long, you'll value in range [1, 6]. you'll try take chamarr[num] - , range of valid indexes [0, 5] arrays 0-based. if try take element 6, give undefined - splicing @ element 6 won't anything.

i change rand method exclusive @ upper bound, this:

function rand(min, max) { return (math.floor(math.random() * (max - min)) + min).tofixed(0); } 

and call this:

num = rand(0, chamarr.length); 

that give value in right range both indexing , splicing.

edit: in response comments etc:

  • it's worth removing tofixed(0) part of rand function; don't really want string, after all. isn't part of wrong before, it's cleaner:

    function rand(min, max) { return math.floor(math.random() * (max - min)) + min; } 
  • you might want version of function makes 0 lower bound implicit

  • if you're not going use random numbers anywhere else in code could inline math.floor() / math.random() calls instead of having separate function, i'd want keep them away "logic" code wants random number , use it.
  • the reason i'd change function having exclusive upper bound more common in computer science - typically goes along 0-indexing things collections. typically write for loops inclusive lower bounds , exclusive lower bounds, etc.

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -