我有24个数据块的数据文件(php),结构如下。
//ts1
$P[] = [0];
$S[] = [[1,95.8172406762736],[2,104.97526726371],[3,112.03839938973],[4,101.70457396977],];
$F[] = [];
$FB[] = [];
//ts2
$P[] = [0];
$S[] = [[1,103.190939795922],[2,105.297198378469],[3,105.829786652111]];
$F[] = [];
$FB[] = [];
//ts3
$P[] = [0];
$S[] = [[1,107.285278217373],[2,103.557795069809],[3,105.686758569246],[4,103.748341353355]];
$F[] = [];
$FB[] = [];
我需要将前12个区块洗牌,然后将区块13-24洗牌。我的代码似乎不起作用,因为它仍然一次洗掉所有24个块。我不确定应该怎么写呢......
// DATA INITIALISATION
// - Reads all data sets from server
// - Generates list of objects
// - Randomises list of objects
function DataInit1()
{
SeriesList = [];
CurrentGraph.Series = 0;
// load all the data sets from server
$.getJSON("datademo.php",
function(Data1)
{
for(var i=0; i<Data1.length; i+=4)
{
var P = Data1[i+0];
var S = Data1[i+1];
var F = Data1[i+2];
var FB = Data1[i+3];
var NewSeries = new SeriesClass(P,S,F,FB);
NewSeries.SeriesNumber = (i/4)+1;
SeriesList.push(NewSeries);
}
}
);
// shuffle each of the series lists to a random order
s1 = SeriesList.length/2;
s2 = SeriesList.length;
for(var i=0; i<s1; i++)
{
var j = Math.floor(Math.random() * (i+1));
var x = SeriesList[i];
SeriesList[i] = SeriesList[j];
SeriesList[j] = x;
}
for(var i=s1; i<s2; i++)
{
var j = Math.floor(Math.random() * (i+1));
var x = SeriesList[i];
SeriesList[i] = SeriesList[j];
SeriesList[j] = x;
}
}
编辑:我现在已将其更改为以下内容(不是很漂亮,但我没有时间整理它)。现在它随机化1-12系列,但系列13-24现在不是随机的。我不经常编码,我不明白为什么它会在第一位而不是第二位工作。
// shuffle the series list to a random order
for(var i=SeriesList.length-13; i>0; i--)
{
var j = Math.floor(Math.random() * (i+1));
var x = SeriesList[i];
SeriesList[i] = SeriesList[j];
SeriesList[j] = x;
}
for(var i={from: 12, to: 23}; i>0; i--)
{
var j = Math.floor(Math.random() * (i+1));
var x = SeriesList[i];
SeriesList[i] = SeriesList[j];
SeriesList[j] = x;
}
答案 0 :(得分:0)
我认为最简单的方法是将其分成两个阵列,将它们分开,然后将它们重新组合在一起。我已经使用了这个问题的shuffle方法:How can I shuffle an array?,以及从How to extend an existing JavaScript array with another array, without creating a new array?加入数组的方法
见https://jsfiddle.net/u25ta64x/1/
的小提琴var SeriesList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26];
var firstHalf = SeriesList.slice(0,13);
var secondHalf = SeriesList.slice(13,26);
function shuffle(a) {
var j, x, i;
for (i = a.length; i; i--) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
}
shuffle(firstHalf);
shuffle(secondHalf)
var shuffledList = firstHalf;
Array.prototype.push.apply(shuffledList, secondHalf);
console.log(shuffledList);