我不知道为什么这段代码不起作用,也没有引发任何错误。
function rotateArray(arr){
return function(){
var newMod = [];
for(let i = 0; i<arr.length; i++){
if(i===0){
newMod[i] = arr[arr.length - 1];
}else{
newMod[i] = arr[i-1];
}
}
return arr = newMod;
}
}
var btns = {
btn1: 1,
btn2: 2,
btn3: 3,
btn6: 6,
btn9: 9,
btn8: 8,
btn7: 7,
btn4: 4,
}
var rotfunc = rotateArray([1,2,3,6,9,8,7,4]);
document.getElementById('btn5').addEventListener('click',() => {
let rot = rotfunc()
for(let i in btns){
btns[i] = rot.shift();
}
for(let i in btns){
document.getElementById(i).innerHTML = btns[i];
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Buttons Grid</title>
<style type="text/css">
.buttonContainer {
width: 75%;
}
.buttonContainer > .buttonClass {
width: 30%;
height: 48px;
font-size: 24px;
}
</style>
</head>
<body>
<div class = "buttonContainer" id = "btns">
<button id = "btn1" class = "buttonClass">1</button>
<button id = "btn2" class = "buttonClass">2</button>
<button id = "btn3" class = "buttonClass">3</button>
<button id = "btn4" class = "buttonClass">4</button>
<button id = "btn5" class = "buttonClass">5</button>
<button id = "btn6" class = "buttonClass">6</button>
<button id = "btn7" class = "buttonClass">7</button>
<button id = "btn8" class = "buttonClass">8</button>
<button id = "btn9" class = "buttonClass">9</button>
</div>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
单击按钮5时,我试图顺时针旋转数字的外圆。但这只会发生一次,然后我将丢失“ rot”数组中的所有值。也许我缺少了一些东西。谁能帮忙?
当调用rot.shift()
时,您正在修改保存在rotfunc
闭包中的数组。因此,下次调用rotfunc()
时,该数组为空。
使用slice()
方法修改数组之前,先对其进行复制。