目录
三、Fisher-Yates 洗牌算法(也被称为 Knuth 洗牌算法)
效果图展示:
一、Array.from()的使用
- Array.from(): 这是一个JavaScript方法,它从一个类似数组或可迭代的对象创建一个新的数组实例。
- { length: 10 }: 这是一个对象,其只有一个属性length,值为10。
- (_, i) => i: 这是一个箭头函数,它有两个参数,第一个参数(_)在这里没有被使用(只是一个占位符)。函数的返回值是第二个参数i,即当前元素的索引。
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const array = Array.from({ length: 10 }, (_, i) => i);
二、Array.forEach()的使用
- Array.forEach(): 这是 JavaScript 中的一个方法,用于遍历数组的每个元素并执行提供的函数。这个方法对数组中的每个元素执行一次提供的函数。
const array = [1, 2, 3, 4, 5];
array.forEach((item, index) => {
console.log(`在索引 ${index} 的元素是 ${item}`);
});
// 在索引 0 的元素是 1
// 在索引 1 的元素是 2
// 在索引 2 的元素是 3
// 在索引 3 的元素是 4
// 在索引 4 的元素是 5
三、Fisher-Yates 洗牌算法(也被称为 Knuth 洗牌算法)
function shuffleArray(array) {
// 从数组的最后一个元素开始向前遍历
for (let i = array.length - 1; i > 0; i--) {
// 生成一个从 0 到 i(包含)的随机整数
const j = Math.floor(Math.random() * (i + 1));
// 交换当前元素 array[i] 和随机索引 j 处的元素 array[j]
[array[i], array[j]] = [array[j], array[i]];
}
}
四、完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shuffle Animation</title>
<style>
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.item {
width: 50px;
height: 50px;
background-color: blue;
margin: 5px;
transition: transform 0.3s ease;
}
</style>
</head>
<body>
<div class="container" id="container"></div>
<button onclick="shuffle()">Shuffle</button>
<script>
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
function render(array) {
const container = document.getElementById('container');
container.innerHTML = '';
array.forEach((item, index) => {
const element = document.createElement('div');
element.classList.add('item');
element.style.order = index;
element.style.transform = `translateX(${index * 60}px)`;
container.appendChild(element);
});
}
function animate(array) {
const items = document.querySelectorAll('.item');
items.forEach((item, index) => {
setTimeout(() => {
item.style.transform = `translateX(${array[index] * 60}px)`;
}, index * 100);
});
}
function shuffle() {
const array = Array.from({ length: 10 }, (_, i) => i);
shuffleArray(array);
render(array);
setTimeout(() => animate(array), 100);
}
</script>
</body>
</html>