简体   繁体   English

使用 jquery 从数组中打印随机元素

[英]Print random elements from an array using jquery

I'm trying to print array elements randomly using jquery functions.我正在尝试使用 jquery 函数随机打印数组元素。 I've generated the random number count using math.random but unable to print array elements in the html document.我使用 math.random 生成了随机数计数,但无法在 html 文档中打印数组元素。 (.print-que) is a class in html which i'm referencing here. (.print-que) 是 html 中的 class ,我在这里引用。 Also there is an identifier expected error while accesing the array elements using jquery object.使用 jquery object 访问数组元素时,还会出现标识符预期错误。 any solutions for this?有什么解决方案吗?

function kidzee() {

    var que = [
        "Click on a circle shaped object",
        "Click on a rectangle shaped object",
        "Click on a triangle shaped object",
        "Click on a square shaped object",
        
    ];
    

    var queArr = que.length;

    

    function generateQuestion() {
        //var len = que.length;
        //Generates random question and displays it
        var queNo = Math.floor((Math.random() * queArr-1) + 0);
        $(".print-que").html( que.[queNo] );
        
    }




    return {
        generateQuestion : generateQuestion
    }
}

var kidzeeInstance = kidzee();
kidzeeInstance.generateQuestion(); 

It does not need jquery.它不需要 jquery。 Just use 'Math.只需使用“数学”。 Random' to get the index you want using javascript.it returns a random number between 0 (inclusive), and 1 (exclusive). Random' 使用 javascript 获取您想要的索引。它返回一个介于 0(包括)和 1(不包括)之间的随机数。 Then you can multiple the value with array length and to have integer value, you can use math.floor or round.然后,您可以将值与数组长度相乘并获得 integer 值,您可以使用 math.floor 或 round。

var number = 1 + Math.floor(Math.random() * length);

You can use this value to access the array randomly.您可以使用此值随机访问数组。 Replace the length variable with the size of array.将长度变量替换为数组的大小。

Can you please try this once - $(".print-que").append(Math.floor(Math.random() * que.length));你能试试这个 - $(".print-que").append(Math.floor(Math.random() * que.length));

Please check que.[queNo] and replace it with que[queNo]请检查que.[queNo]并将其替换为que[queNo]

$(".print-que").html( que[queNo] );

 function kidzee() { var que = [ "Click on a circle shaped object", "Click on a rectangle shaped object", "Click on a triangle shaped object", "Click on a square shaped object" ]; var queArr = que.length; function generateQuestion() { //var len = que.length; //Generates random question and displays it var queNo = Math.floor((Math.random() * queArr-1) + 0); $(".print-que").html( que[queNo] ); } return { generateQuestion: generateQuestion } } var kidzeeInstance = kidzee(); kidzeeInstance.generateQuestion();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="print-que"> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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