【问题标题】:Random select array with remove items (jQuery)带有删除项目的随机选择数组(jQuery)
【发布时间】:2016-06-07 09:05:05
【问题描述】:

我试图找到一种从随机数组中获取值而不重复它们的方法,我找到了以下解决方案:

var letters = ["A", "B", "C"];
var getRandom = (function(array) {
  var notGivenItems = array.map(function(el) {
    return el;
  });
  var getIndex = function() {
    return Math.floor(Math.random() * notGivenItems.length);
  };

  return function() {
    if (notGivenItems.length === 0) {
      return;
    }

    return notGivenItems.splice(getIndex(), 1)[0];
  };
})(letters);

console.log(getRandom());
console.log(getRandom());
console.log(getRandom());
console.log(getRandom());

如果我打印console.log() 4 次,最后,数组显示为undefined,这正是我需要的。但是,我需要 (function () {... 不要自动触发,因为来自 AJAX 的值。所以,应该是这样的:

function selec() {

  var getRandom = (function(array) {
    var notGivenItems = array.map(function(el) {
      return el;
    });
    var getIndex = function() {
      return Math.floor(Math.random() * notGivenItems.length);
    };

    return function() {
      if (notGivenItems.length === 0) {
        return;
      }

      return notGivenItems.splice(getIndex(), 1)[0];
    };
  })(letters);

  return getRandom();
}

console.log(selec());

然后,函数继续连续打印值,不返回undefined

【问题讨论】:

  • 您是在内部声明letters 还是在外部selec() 声明?
  • Out,因为如果在里面,当再次运行select()时,letters恢复到原来的格式。
  • 每次调用selec() 时,都会从letters 重新初始化array
  • because the value that comes via AJAX... 哪个值? letters?另外,当您致电console.log(selec()); 时,您究竟期待什么?
  • “来自 AJAX”是什么意思?你的第一个功能应该是一样的

标签: javascript arrays function random


【解决方案1】:

我希望我已经理解了您的问题。如果是,那真的很容易。检查这个fiddle

var letters = ["A", "B", "C"];

function getRandom(array){
  var notGivenItems = array.map(function(el){
    return el;
  });
  var getIndex=function(){
    return Math.floor(Math.random() * notGivenItems.length)
  };
  if (notGivenItems.length === 0)
    return;
  return array.splice(getIndex(), 1)[0];
}

console.log(getRandom(letters));
console.log(getRandom(letters));
console.log(getRandom(letters));
console.log(getRandom(letters));

【讨论】:

  • 我经常说,如果一个问题太难了,那是因为你做错了。真的很简单,谢谢!
【解决方案2】:

发生的情况是,每次调用 selec() 时,它都会重新创建 getRandom 函数。

您需要做的是在selec() 函数范围之外定义getRandom

你可以在同一级别做到这一点:

var getRandom = (function(array) { ... })(letters);
var selec = function() { return getRandom; };

或者你可以创建一个闭包来保护getRandom免受命名冲突:

var selec = (function() {
    var getRandom = (function(array) { ... })(letters);
    return function() { return getRandom; };
})();

【讨论】:

  • 这很好用。刚刚将return getRandom; 更改为return getRandom (); 但是,对于我使用AJAX 的情况,如下所示:$ .AJAX ({ type: ' GET ', URL: ' json ', questions. datatype: ' json ', success: function (data) { var arr = []; for (var index in data) { arr. push (index ++); } window.ind = arr; } })window.ind 覆盖letters 时,数组变为undefined。再次感谢!
猜你喜欢
  • 2015-04-07
  • 2020-07-01
  • 2021-11-06
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 2021-05-04
相关资源
最近更新 更多