一、不使用额外空间
思路:随机交换
Array.prototype.shuffle = function () {
var array = this;
for (var i = array.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = array[randomIndex];
array[randomIndex] = array[i];
array[i] = itemAtIndex;
}
return array;
};
二、使用额外空间
思路:每次随机从数组抽出一个数, 放进新数组, 然后将这个数从原数组中删除
Array.prototype.shuffle = function () {
var array = this
var len = array.length
var newArray = []
while (len > 0) {
var randomIndex = Math.floor(Math.random() * len)
var itemAtIndex = array[randomIndex]
newArray.push(itemAtIndex)
array.splice(randomIndex, 1)
len--
}
return newArray
}
随机数组的应用:随机展示页面数据
方法一:劫持数据的改变
var app = {
render (data) {
...
},
shuffle () {
this.list = this.list.shuffle()
}
}
Object.defineProperty(app, 'list', {
get () {
return this._list
},
set (data) {
if (!Array.isArray(data)) return
this._list = data
this.render(this._list)
}
})
// 请求后端数据, 并渲染
fetch(...)
.then(response => response.json())
.then(data => {
app.list = data
})
// 随机后, 渲染
app.shuffle()
方法二:class
class App {
constructor (list) { // 初始化
this.list = list
}
get list () {
return this._list
}
set list (data) {
if (!Array.isArray(data)) return
this._list = data
this.render(this._list)
}
render (data) {
...
}
shuffle () {
this.list = this.list.shuffle()
}
}
let app = new App()
// 请求后端数据, 并渲染
fetch(...)
.then(response => response.json())
.then(data => {
app.list = data
})
// 随机后, 渲染
app.shuffle()