写php的时候 有个shuffle 函数很爽很好用,但是js要实现同样算法的时候发现没有现成函数,在网上看了大量的例子,觉得不靠谱所以,自己写了一个,其实非常简单,以下是实现代码
var shuffle = function (arrBox) {
arrBox = typeof arrBox === "string" ? arrBox.split("") : arrBox;
//实现一个洗牌算法
var shuffleBox = []
var len = arrBox.length;
for (i = 0; i < len; i++) {
var boxIndex = Math.floor(Math.random() * arrBox.length);
shuffleBox.push(arrBox[boxIndex].valueOf());
arrBox.splice(boxIndex, 1);
}
return shuffleBox;
}
var data = new Arra
示例
shuffle("abcdefghijklmnuvwxyz".split(""));
//结果显示
["g", "u", "x", "k", "y", "f", "v", "l", "j", "n", "b", "z", "w", "d", "c", "e", "a", "h", "i", "m"]
shuffle("abcdefghijklmnuvwxyz".split(""));
//结果显示
["a", "j", "m", "f", "g", "h", "c", "l", "v", "x", "w", "u", "k", "d", "e", "b", "n", "y", "z", "i"]
说明:有的朋友可能觉得我的参数并不是数组,其实是这样的 在console中执行:
"abcdefghijklmnuvwxyz".split("")
//输出
["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "u", "v", "w", "x", "y", "z"]
还有一个随机字符串的算法
randStr = (randLen, split, toUpper, str) => {
let shuffle = function (arrBox) {
arrBox = typeof arrBox === "string" ? arrBox.split("") : arrBox;
let shuffleBox = []
let len = arrBox.length;
for (let i = 0; i < len; i++) {
let boxIndex = Math.floor(Math.random() * arrBox.length);
shuffleBox.push(arrBox[boxIndex].valueOf());
arrBox.splice(boxIndex, 1);
}
return shuffleBox;
}
str = str || "abcdefghigklmnopkrstuvwxyz";
randLen=randLen||3;
randLen = randLen > str.length - 1 ? str.length - 1 : randLen;
let randKey = [
(new Date().getTime()).toString(32),
shuffle(str).splice(Math.floor(Math.random() * (str.length - randLen - 1)), randLen).join("")
];
let res = randKey.join(split || "");
return toUpper ? res.toUpperCase() : res;//生成一个随机不重复key
}