我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
我有一个这样的数组:
var arr1 = ["a", "b", "c", "d"];
我如何随机化/打乱它?
当前回答
// Create a places array which holds the index for each item in the
// passed in array.
//
// Then return a new array by randomly selecting items from the
// passed in array by referencing the places array item. Removing that
// places item each time though.
function shuffle(array) {
let places = array.map((item, index) => index);
return array.map((item, index, array) => {
const random_index = Math.floor(Math.random() * places.length);
const places_value = places[random_index];
places.splice(random_index, 1);
return array[places_value];
})
}
其他回答
随机化数组
var arr = ['apple','cat','Adam','123','Zorro','petunia'];
var n = arr.length; var tempArr = [];
for ( var i = 0; i < n-1; i++ ) {
// The following line removes one random element from arr
// and pushes it onto tempArr
tempArr.push(arr.splice(Math.floor(Math.random()*arr.length),1)[0]);
}
// Push the remaining item onto tempArr
tempArr.push(arr[0]);
arr=tempArr;
或者像上面所有的答案,但简而言之。
function shuffle(a) { for (var c, d, b = a.length; 0 !== b;)d = Math.floor(Math.random() * b), b -= 1, c = a[b], a[b] = a[d], a[d] = c; return a }
//one line solution
shuffle = (array) => array.sort(() => Math.random() - 0.5);
//Demo
let arr = [1, 2, 3];
shuffle(arr);
alert(arr);
https://javascript.info/task/shuffle
Math.random()-0.5是一个随机数,可以是正数或负,所以排序函数会随机地重新排序元素。
您可以通过以下方式轻松完成:
//阵列var fruits=[“香蕉”、“橙色”、“苹果”、“芒果”];//随机的,随机的fruits.sort(函数(a,b){return 0.5-Math.random()});//输出console.log(水果);
请参考JavaScript排序数组
我使用以下两种方法:
此方法不会修改原始数组
shuffle(array);
功能洗牌(arr){var len=arr.length;var d=长度;var数组=[];变量k,i;对于(i=0;i<d;i++){k=数学楼层(Math.random()*len);array.push(arr[k]);arr.splice(k,1);len=排列长度;}对于(i=0;i<d;i++){arr[i]=阵列[i];}返回arr;}var arr=[“a”,“b”,“c”,“d”];arr=洗牌(arr);控制台日志(arr);
此方法修改原始数组
array.shuffle();
Array.prototype.shuffle=函数(){var len=此长度;var d=长度;var数组=[];变量k,i;对于(i=0;i<d;i++){k=数学楼层(Math.random()*len);array.push(this[k]);此接头(k,1);len=此长度;}对于(i=0;i<d;i++){this[i]=数组[i];}}var arr=[“a”,“b”,“c”,“d”];arr.shuffle();控制台日志(arr);