javascript 数组随机排序 洗牌算法
1、
function shuffle(a) { var b = []; while (a.length) { var index = ~~(Math.random() * a.length); b.push(a[index]); a.splice(index, 1); } return b; }
2、
function shuffle(a) { var length = a.length; var shuffled = Array(length); for (var index = 0, rand; index < length; index++) { var random = Math.random() * (index + 1); rand = ~~(random); rand_ = Math.floor(random); console.log(random); console.log(rand); console.log(rand_); // if (rand !== index) shuffled[index] = shuffled[rand]; shuffled[rand] = a[index]; } return shuffled; }
3、
function shuffle(array) { var _array = array.concat(); for (var i = _array.length; i--; ) { var random = Math.random(); var j = Math.floor(random * (i + 1)); console.log("i:"+i); console.log("j:"+j); console.log("random:"+random); console.log("=================================="); var temp = _array[i]; _array[i] = _array[j]; _array[j] = temp; } return _array; }