如何从数组中返回随机值? [英] How can I return a random value from an array?

查看:131
本文介绍了如何从数组中返回随机值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery validate插件,并希望在成功时返回一个随机值。

I'm using the jQuery validate plugin, and would like to return a random value on success.

现在我正在尝试使用:

     var success_message = new Array ();
     success_message[0] = "Good!";
     success_message[1] = "Ok!";
     success_message[2] = "Great!";
     success_message[3] = "Perfect!";
     success_message[4] = "Nice!";
     success_message[5] = "Awesome"; 
     var i = Math.floor(5*Math.random())

然后在哪里我需要输出我使用的值:

Then where I need to output the value I use:

 $(document).ready(function(){
     var validator = $(".contactform").validate({
        success: function(label) {
           label.addClass("valid").text(success_message[i])
        }
     }); //end form validate code
 });

这会选择一个随机值,但对每个成功消息使用相同的值,而不是为其选择不同的值每个字段。

This selects a random value but uses the same value for each success message instead of selecting a different one for each field.

推荐答案

您可以存储消息数组并计算消息显示你去,像这样:

You can store the messages array and calculate the message to show as you go, like this:

var messages = ["Good!", "Great!", "Awesome!", "Super!", "Nice!"];
function getMessage() {
   return messages[Math.floor(Math.random() * messages.length)];
}

在这里尝试一下,然后在 getMessage text /rel =noreferrer> .text() 调用,如下所示:

Give it a try here, then just call getMessage in your .text() call, like this:

label.addClass("valid").text(getMessage());

这篇关于如何从数组中返回随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆