jeudi 17 août 2017

Javascript - function returning unexpected results

I am writing a couple of javascript functions to help randomly select articles from a JSON feed.

I have created a function called getRandomNumberFromRange which takes 2 parameters: the minimum and maximum numbers of a range of numbers to select from. The number of articles to be selected at random is provided via a data attribute on the DOM element which will eventually be populated with the articles.

The second function loadStories loops through the amount of articles which needs to be retrieved and calls the getRandomNumberFromRange function to get a number. This number will eventually be used as a key to select articles from the JSON feed array.

To ensure that a random number is not picked more than once, I have created an array to store previously picked numbers, which I will check against when the number is picked. If the number is in the array already, another number is picked, if it isn't it is added to the array.

This Codepen shows what I have so far. The code is also shown below:

var setupEmployeeStories = function () {
    var
    $element = $(".related-employee-stories"),
    noOfStories = parseInt($element.attr("data-stories")),
    arrSelectedNumbers = [],

    getRandomNumberFromRange = function(min, max) {

        var randomNumber = Math.floor(Math.random() * (max - min) + min);

        if(arrSelectedNumbers.indexOf(randomNumber) === -1){
            arrSelectedNumbers.push(randomNumber);
        }else{
            getRandomNumberFromRange(min, max);
        }

        return randomNumber;
   },

   loadStories = function(){
       for(var i = 0; i < noOfStories; i++){
           var rand = getRandomNumberFromRange(0, 4);
           console.log(rand);
       }

       console.log(arrSelectedNumbers);
   };

   loadStories();

 };

 setupEmployeeStories();

Unfortunately I'm getting some odd results from the functions when the functions select the same random number multiple times. For some reason getRandomNumberFromRange tends to return a completely different number than what was actually picked by the function. This can be seen by the differences in the (console) logged results and the final array - arrSelectedNumbers




Aucun commentaire:

Enregistrer un commentaire