【问题标题】:Randomize and split object into 2 arrays将对象随机化并拆分为 2 个数组
【发布时间】:2016-09-16 22:19:50
【问题描述】:

我有一个包含 8 个项目的对象 - 我想将这些项目分成 2 个数组(随机)。

我想要达到的目标

对象:{1、2、3、4、5、6}:编码

从对象,它应该自动创建 2 个单独的数组,并获取对象项并将它们随机化到数组中。确保它不会重复。

数组 1:[3, 5, 6]

数组 2:[2, 1, 4]

到目前为止的代码:

var element = {
  1: {
    "name": "One element",
    "other": 10
  },
  2: {
    "name": "Two element",
    "other": 20
  },
  3: {
    "name": "Three element",
    "other": 30
  },
  4: {
    "name": "Four element",
    "other": 40
  },
  5: {
    "name": "Five element",
    "other": 50
  },
  6: {
    "name": "Six element",
    "other": 60
  },
  7: {
    "name": "Seven element",
    "other": 70
  },
  8: {
    "name": "Eight element",
    "other": 80
  }
};

function pickRandomProperty(obj) {
  var result;
  var count = 0;
  for (var prop in obj)
    if (Math.random() < 1 / ++count)
      result = prop;
  return result;
}



console.log(pickRandomProperty(element));

【问题讨论】:

  • 如何获得随机元素?
  • 您当前的代码有什么问题;什么是正确的,什么是错误的?
  • 上面的代码没有问题,我只需要帮助尝试将对象分成 2 个数组,如上所示的示例。找出最好的解决方法

标签: javascript jquery arrays random


【解决方案1】:

确保您的对象变量是一个数组。 var element = [...你的物品]; 不确定你所拥有的是否有用: var element = {...your items...}; 您可以使用此代码对数组进行洗牌(事实上的无偏洗牌算法是 Fisher-Yates(又名 Knuth)洗牌。):How to randomize (shuffle) a JavaScript array?

function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;  
while (0 !== currentIndex) {

// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}

然后像这样拼接(Splice an array in half, no matter the size?):

    var half_length = Math.ceil(arrayName.length / 2);    
    var leftSide = arrayName.splice(0,half_length);

您的原始数组将包含剩余的值。

【讨论】:

  • 谢谢,但这不会随机化。
  • 这个答案有两个部分。您是否尝试过第一个链接中的随机播放代码?我将编辑以包含它。
【解决方案2】:

你的 if 逻辑没有意义。

if (Math.random() &lt; 1 / ++count)

Math.random() 将产生 0(包括)和 1(不包括)之间的任何值。 http://www.w3schools.com/jsref/jsref_random.asp

您的函数没有做任何事情来创建具有随机值的数组。

【讨论】:

    猜你喜欢
    • 2014-03-11
    • 2015-10-16
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多