这两天面试遇到的一道面试题……
解题思路: 每次从原始数组中随机选取一个元素,可以理解为每次取出元素的索引值是数组所有索引值的一个随机值, 所以不难得出取出的索引值为Math.floor(Math.random()*array.length); 然后每次取出一个元素后,都要将其从原始数组里移除,数组长度就会减一
代码实现:
function shuffle(array) {
let res = [], random;
while(array.length > 0) {
random = Math.floor(Math.random()*array.length);
res.push(array[random]);
array.splice(random, 1);
}
return res;
}
let res = shuffle([1,2,3,4,5,6]);
console.log(res);
let res2 = shuffle([1,2,3,4,5,6]);
console.log(res2);
测试结果: