简体   繁体   中英

Trying to generate a random integer within a specific range then have it displayed inline

So, here's what I have (I am running JQuery):

http://jsfiddle.net/KDmwn/111/

The computer chose <span id="x"></span>. 
$(document).ready(function () {
    var x = function getRandomInt(1, 4) {
        return Math.floor(Math.random() * (4 - 1 + 1)) + 1
    };
    $('#x').html(x);
}

I feel like the issue has to do with this $('#x').html(x);

Any help is much appreciated. Thanks!

The issue is because your x function has two integers set as the arguments, which is syntactically incorrect.

To achieve what you need you should remove the integers in the argument list, fix the mis-matched bracket at the end of the DOMReady handler and you can also remove the - 1 + 1 from the Math.random value.

Try this:

var x = function getRandomInt() {
    return Math.floor(Math.random() * 4) + 1;
}
$('#x').html(x);

Updated fiddle

Use below code

$('#x').html(Math.floor(Math.random() * 4 ) + 1);

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM