在jquery中,怎么可能用条件随机化一个数组?

In jquery, how is it possible to randomize an Array with conditions?

我这样随机排列数组的顺序:

var arr = [ "A","B","C","D","E","F" ]
arr.sort(function() { return 0.5 - Math.random() });

// produces for example : [ C, E, A, F, D, B ]

但是我想要"F"在第四个位置(例如)。

解决方法是什么?

可以在调用 .sort() 之前使用 .pop() 从数组中删除 "F" ,使用 .splice() 在除索引 [=16= 之外的任何位置重新插入 "F" ] 共 arr 使用第二个数组,其中包含 arr 的所有索引,不包括 3

var arr = [ "A","B","C","D","E","F" ];
var not = [0,1,2,4,5];
var f = arr.pop();
arr.sort(function() { return 0.5 - Math.random() });
var p = not[Math.floor(Math.random() * not.length)];
arr.splice(p, 0, f);
document.body.innerHTML = arr.join(" ")