如何实现点击时数组中元素X处于索引0时保持位置不变
问题描述
我需要实现点击按钮时,数组中的元素"X"向下移动一个索引位置。例如数组[0, 1, 2, "X", 4]点击后应变为[0, 1, "X", 3, 4];但当"X"处于索引0(如["X", 1, 2, 3, 4])时,点击后它不应改变位置。目前我的代码在"X"处于索引0时,它会跳转到数组最高索引位置,尝试修改后仍未解决,现有代码如下:
现有代码
JavaScript
// array let player1gameboard2 = ["X", 1, 2, 3, 4, 5, 6] function changePositionPlayer1Down(player1gameboard2) { // prints out array console.log(player1gameboard2) document.getElementById("player1_test").innerHTML = player1gameboard2 // condition if array is less than 1. Normally goes to highest index. should just stay at lowest index if (player1gameboard2.indexOf("X") === 0) { player1gameboard2.splice( //future index of element 0, // original element 0, // how to get original element // [0] means it is an array // means 1 element player1gameboard2.splice(0, 1)[0] ) // prints out new array document.getElementById("player1_test").innerHTML = player1gameboard2 } }
HTML
<!-- Array printed out on screen --> <p id="player1_test"></p> <!-- every time button clicked, indexed array goes down one space --> <button onclick="changePositionPlayer1Down(player1gameboard2)">Go Down</button>
问题分析
你的代码存在两个核心问题:
- 缺少正常移动逻辑:当前函数仅处理了
"X"在索引0的情况,完全没有实现"X"在其他位置时向下移动的代码。 - 索引0的处理逻辑冗余:你用
splice先移除索引0的元素又插回原位置,属于无效操作;如果之前的代码是把元素插入到数组末尾,就会导致"X"跳到最后。
修正后的代码
实现逻辑
- 找到
"X"的当前索引currentIdx - 如果
"X"在索引0或数组最后一位,直接返回不做操作 - 移除
"X",将其插入到当前索引+1的位置,实现向下移动 - 单独封装DOM更新逻辑,避免重复代码
完整代码
JavaScript
let player1gameboard2 = ["X", 1, 2, 3, 4, 5, 6] function changePositionPlayer1Down() { const currentIdx = player1gameboard2.indexOf("X"); // 处理X不存在、在开头、在结尾的边界情况 if (currentIdx === -1 || currentIdx === 0 || currentIdx === player1gameboard2.length - 1) { updateDisplay(); return; } // 移除X并插入到下一个索引位置 const [xElement] = player1gameboard2.splice(currentIdx, 1); player1gameboard2.splice(currentIdx + 1, 0, xElement); updateDisplay(); } // 封装更新页面显示的函数 function updateDisplay() { console.log(player1gameboard2); document.getElementById("player1_test").textContent = player1gameboard2.join(", "); } // 页面加载时初始化显示 updateDisplay();
HTML
<p id="player1_test"></p> <button onclick="changePositionPlayer1Down()">Go Down</button>
说明
- 用
join(", ")格式化数组显示,比直接转字符串更易读 - 移除了函数参数中的数组,全局变量无需重复传入
- 增加了边界判断,避免无效操作和异常情况
内容的提问来源于stack exchange,提问作者Gabby Gouin
相关产品推荐
相关产品推荐

