2

些細な質問。私がこれまでに持っているものhttp://jsfiddle.net/Dth2y/1/

タスク、次のボタンは、配列から値をランダムに選択し、その値を配列から削除する必要があります。これまでは getNames 関数を呼び出していましたが、この関数内で、配列からランダムに選択された値も、html に追加された後に削除する必要があります。

HTML

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

</p>

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())

     });
 });

</p>

splice メソッドを使用して同様の質問を見たことがあります。バージョンを一緒にハックしようとしましたが、より効率的な方法があるかどうか疑問に思っています。

4

2 に答える 2

2

これを確認してください: 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);
};

ここではフィドルに適用されます: http://jsfiddle.net/Dth2y/3/

于 2012-12-22T20:58:52.840 に答える