【问题标题】:Remember last n items in jQuery记住 jQuery 中的最后 n 个项目
【发布时间】:2011-11-19 19:06:51
【问题描述】:

我有一些代码可以从列表中随机突出显示一个名字(这很有效 - 请参阅 this fiddle):

function pickRandom() {
  var random = Math.floor(Math.random() * 6);
  $('.stname').css('background','none').eq(random).css('background','yellow');
}

但我想确保不会一遍又一遍地出现相同的名字。所以我打算记住最后 3 个选择的索引作为黑名单:

var recentlyAsked = new Array();
function pickRandom() {
  var random;
  do {
    random = Math.floor(Math.random() * 6);
  } while ($.inArray(random,recentlyAsked));
  recentlyAsked.push(random);
  if (recentlyAsked.length >= 4) recentlyAsked.shift();
  $('.stname').css('background','none').eq(random).css('background','yellow');
}

这不起作用;见this fiddle警告:它会导致浏览器挂起。

有什么建议吗?

【问题讨论】:

  • 您的浏览器挂起,因为循环没有停止。该警告实际上非常有用,但我怀疑有人会看到您链接到的小提琴:)

标签: javascript jquery arrays queue


【解决方案1】:
do {
    random = Math.floor(Math.random() * 6);
  } while ($.inArray(random,recentlyAsked));

永远运行,因为inArray 在数组中找不到项目时返回-1,这是一个真实值。 0 是唯一一个虚假值的数字。你的数组最初是空的,所以什么也找不到。

用:修复它:

do {
    random = Math.floor(Math.random() * 6);
  } while ($.inArray(random,recentlyAsked) > -1);

当它返回-1(未找到)时,这将停止

【讨论】:

    【解决方案2】:
    var ids=['a','b','c'];
    var old=['d','e','f'];//At the beginning this will need populated with 3 random values
    var ran=Math.floor(Math.random() * ids.length);
    var ele=ids.splice(ran,1);
    old.push(ele);
    ids.push(old.shift());
    highlight(ele);
    

    这是一种稍微替代的方法来做你想做的事。这个想法只是删除选定的元素,然后将其添加回原始数组。

    【讨论】:

      【解决方案3】:

      只是想我会把我的代码扔出去:

      var randomArray = new Array(0, 1, 2, 3, 4, 5);
      var pastArray = new Array();
      
      function pickRandom() {
          var random = Math.floor(Math.random() * randomArray.length);
          $('.stname').css('background', 'none').eq(randomArray[random]).css('background', 'yellow');
      
          if (pastArray.length < 3) {
              pastArray.unshift(randomArray[random]);
              randomArray.splice(random, 1);
          } else {
              pastArray.unshift(randomArray[random]);
              randomArray.splice(random, 1, pastArray.pop());
          }
          console.log("possible values: [" + randomArray + "]");
          console.log("past values: [" + pastArray + "]");
      }
      

      值从当前值和过去值来回移动。无需将值预填充为“过去”,因此它开始时是真正随机的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-29
        • 1970-01-01
        相关资源
        最近更新 更多