0

I'm trying to create a loop, for three random sets of numbers that load into an three different unordered lists.

Each list should have three unique random numbers. I'm close, however my code is loading the same numbers, and I tried to do a for loop, but it appears to be loading the same array, and I want three random unique arrays.

$(document).ready(function () {
    var arr = [];
    for (var i = 0, l = 4; i < l; i++) {
        rand = Math.random(3, 7).toFixed(2);
        arr.push('<li>' + 10 + rand * 1 + '</li>')
        $("." + i).append(arr);
    };
});

jsFiddle

3
  • 1
    Math.random does not take any arguments? What are 3,7 supposed to do? Commented Sep 17, 2014 at 14:04
  • 1
    Yes, you have only one arr, and load that same array into all the lists. What else did you expect? Commented Sep 17, 2014 at 14:06
  • I thought 3,7 would choose a number between 3 and 7. I also was thinking of arr i++ but not sure how to define that. Commented Sep 17, 2014 at 14:07

3 Answers 3

1

@Bergi is correct. If you want a number between 3 and 7, one way to implement it is 3 + 4 * Math.random(), since Math.random() will return a number between 0 and 1 (excluding 1).

Also, if you want to create a unique list for each ul, you can iterate over each ul and create a list for it like such:

var $lists = $(".1,.2,.3");
$lists.each(function(index, list) {
    var arr = [];
    for (var i = 0, l = 4; i < l; i++) {
        rand = (3+4*Math.random()).toFixed(2);
        arr.push('<li>'+10+ rand * 1+'</li>')
    }
    $(list).append(arr);
});

Fiddle here: http://jsfiddle.net/qpnf7pog/2/

Sign up to request clarification or add additional context in comments.

Comments

1

You can try this:

$( document ).ready(function() {
var arr = [];
for (var i = 0, l = 1; l < 4; i++) {
    if (i > 0 && i % 3 == 0)
    {
        $(".list"+l).append(arr);
        arr = [];
        l++;
    }

    rand = Math.floor(Math.random()*(7-3+1)+3); // random number between 3 and 7
    arr.push('<li>'+ rand +'</li>');

};

});

http://jsfiddle.net/qpnf7pog/3/

Assuming those random numbers should be in 3-7 range. Hope it helps.

Comments

0

I think what you want to do is use var randomnumber=Math.floor(Math.random()*11). Here is the documentation: http://www.javascriptkit.com/javatutors/randomnum.shtml and Math.floor(): http://www.w3schools.com/jsref/jsref_floor.asp this will allow to specify a max random number only as high as what's after the *.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.