应用场景:根据时间匹配歌词
1. 在数组中定位随机数所在的索引,随机数通过循环遍历数组进行对比,当数组的数大于随机数时,把索引 -1 就得到了随机数的索引。
2. 设置默认索引为(数组长度 -1)防止取不到索引。
3. 如果取到的索引为 -1,直接 return。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button class="btn">随机数</button>
<script>
// 1.定义数据
const values = [100, 300, 500, 800, 1200]
// 2.监听按钮的点击
const btn = document.querySelector('.btn')
btn.onclick = function () {
// 生成随机数
let currentValue = Math.floor(Math.random() * 1500)
// console.log(currentValue)
matchIndex(currentValue)
}
// 3.封装函数:根据 value 去匹配索引
function matchIndex(currentValue) {
let currentIndex = values.length - 1
for (let i = 0; i < values.length; i++) {
const value = values[i]
if (value > currentValue) {
currentIndex = i - 1
break
}
}
if (currentIndex === -1) return
console.log('currentValue:', currentValue, 'index:', currentIndex)
}
</script>
</body>
</html>