js将数组的顺序打乱


最近在网上看到一道面试题,如何将一个数组更高效的打乱它的顺序,无聊之时拿来测试了一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 生成原数组
const arr1 = new Array(100000).fill(null).map((value, index) => index + 1)
const arr2 = new Array(100000).fill(null).map((value, index) => index + 1)
// 方法1:
const fn1 = function(arr) {
return arr.sort(_ => 0.5 - Math.random())
}
// 方法2:
const fn2 = function(arr) {
for (let i = arr.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1))
var itemAtIndex = arr[randomIndex]
arr[randomIndex] = arr[i]
arr[i] = itemAtIndex
}
return arr
}
// 测试:
console.time('fn1')
var result1 = fn1(arr1)
console.timeEnd('fn1')
console.time('fn2')
var result2 = fn2(arr2)
console.timeEnd('fn2')
console.log(result1)
console.log(result2)

结果如下:
1543025476(1)

个人感觉,方法2更加靠谱一些,虽然方法1看起来简洁,原因如下:

  • 不管如何测试方法2耗时更短(在chrome上面)
  • 方法2感觉打乱的更加彻底
  • V8在处理sort时,并不是完全随机(网上指出来的,本人没有研究,参考V8链接

在网上搜索一下,果真在知乎上面有人在讨论:查看链接

如有不同看法,欢迎指正。

坚持原创技术分享,您的支持将鼓励我继续创作!