随机选择价值形态阵列和删除阵列这个值

随机选择价值形态阵列和删除阵列这个值

本文介绍了随机选择价值形态阵列和删除阵列这个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

平凡的问题。我至今

任务,接下来的按钮应该随机选择从阵列中值和数组中删除该值。到目前为止,这叫做getNames函数,这个函数内从数组中随机抽取值应该太被附加到HTML后删除。

Task, the next button should randomly select a value from the array and remove that value from the array. So far this called the getNames function, within this function the value randomly selected from the array should be removed too after being appended to the html.

HTML

<h1 id="name">Click Next To Start</h1> <button id="next">NEXT NAME</button> <button>SKIP NAME</button>

JS

     $(document).ready(function() {
     var names = [
         "Paul",
         "Louise",
         "Adam",
         "Lewis",
         "Rachel"
     ];

     function getNames() {
        return names[Math.floor(Math.random() * names.length)];

     }

             $("#next").click(function() {
                 $('#name').text(getNames())

     });
 });

我见过用拼接的方法类似的问题,我试图破解版本一起,但我想知道如果有一个更有效的方法。

I have seen similar questions using the splice method, I have tried to hack a version together but am wondering if there's a more efficient way.

推荐答案

您将要检查了这一点:的

you will want to check this out: http://ejohn.org/blog/javascript-array-remove/

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

在这里将它应用到你的提琴:

这篇关于随机选择价值形态阵列和删除阵列这个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:32