随机化并拆分对象为2个数组
Randomize and split object into 2 arrays
我有一个对象,有8个项目-我想把这些项目分成2个数组(随机)。
我想要实现的:
:{1,2,3,4,5,6}:harcoded
From object,它应该自动创建2个单独的数组,并将对象项随机分配到数组中。确保它不会重复。
array 1: [3,5,6]
array 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));
确保对象变量是一个数组。Var element =[…];不确定您是否有将工作:var元素={…你的物品…};您可以使用这段代码来洗牌您的数组(事实上的无偏洗牌算法是Fisher-Yates (aka Knuth) shuffle .):如何随机(洗牌)一个JavaScript数组?
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;
}
然后像这样将它拼接(将数组拼接成两半,无论大小?):
var half_length = Math.ceil(arrayName.length / 2);
var leftSide = arrayName.splice(0,half_length);
原始数组将包含剩余的值
你的if逻辑没有意义。
if (Math.random() < 1 / ++count)
Math.random()将得到0(包含)到1(不包含)之间的任何值。http://www.w3schools.com/jsref/jsref_random.asp
你的函数没有做任何事情来创建随机值的数组。
相关文章:
- 如何使用 node.js 比较两个 json 数组
- 用每小时的差值填充数组/列表-从下拉列表中给定两个时间值
- MongoDB (php) - 以数组而不是多个属性的形式返回文档属性
- 在数组中的一个元素上设置多个值
- 访问$.ajax()函数中的两个不同数组
- 在对象数组中查找多个值的d3范围
- 正在更新mongod中两个对象内部的数组
- 如何循环通过2个对象数组并通过匹配id进行合并
- 如何使用javascript合并两个对象数组
- 使用filter和map方法将数组中某些元素的第一个字母大写-JavaScript
- 第一个字第一个字符第二个字第二个字符,一直到数组结束
- 在数组JS中查找三个重复项
- 我正在尝试使用多个2数组来绑定svg圆的数据,但不知道如何绑定
- JS:从整个数组中每次得到5个项目,并得到平均值
- 带有多个答案选项的Javascript动态数组窗口
- 使用数据数组创建多个类似组件
- 如何从数组中删除几个相同的项
- 根据多个值筛选数组
- 创建具有2个唯一数字的Javascript数组
- 在 JQuery 验证中验证多个“数组命名”文件输入和下拉列表