Javascript 如何从数组中返回随机值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3419928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:32:38  来源:igfitidea点击:

How can I return a random value from an array?

javascript

提问by Brooke.

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

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

Right now I'm trying to use:

现在我正在尝试使用:

     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.

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

回答by Nick Craver

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

您可以存储messages数组并计算要随时显示的消息,如下所示:

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

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

在这里试一试,然后只需拨打getMessage您的.text()电话,如下所示:

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

回答by Rakesh Kumar

We can add Method to Array.

我们可以将方法添加到数组。

Array.prototype.getRandomVal = function(){
    return this[Math.floor(Math.random()*this.length)];
};

messages.getRandomVal();

回答by Mike Sherov

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

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