我有一个包含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));
答案 0 :(得分:1)
确保您的对象变量是一个数组。 var element = [... youritems]; 不确定你的工作是否有效:var element = {... your items ...}; 您可以使用此代码来混淆您的数组(事实上无偏见的随机播放算法是Fisher-Yates(又名Knuth)Shuffle。):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);
您的原始数组将包含其余值。
答案 1 :(得分:-2)
你的逻辑没有意义。
if (Math.random() < 1 / ++count)
Math.random()将产生0(包括)和1(不包括)之间的任何值。 http://www.w3schools.com/jsref/jsref_random.asp
您的函数没有做任何事情来创建具有随机值的数组。