push 新增阵列新元素至阵列后方

unshift 新增阵列新元素至阵列前方

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>阵列的push、unshift
</title>
</head>
<body>
<div class="wrap">
<button class="leftBTN">上一张</button>
<h2 class="text">尚未有内容</h2>
<button class="rightBTN">下一张</button>
<h2 class="pageIdxNUM">1/5</h2>
</div>
<script>
// 步骤 2:JavaScript 变数初始化
const leftBTN = document.querySelector(".leftBTN");
const rightBTN = document.querySelector(".rightBTN");
const pageIdxNUM = document.querySelector(".pageIdxNUM");
const text = document.querySelector(".text");

// 步骤 3:初始化页面索引和内容阵列
let pageIdx = 0;
const Arr = ["你好吗???", "我是XXXX", "很高兴认识你"];

// 添加新内容到阵列
Arr.push("push ,往后塞");
Arr.unshift("unshift,往前塞");

// 步骤 4:添加按钮点击事件处理器
leftBTN.addEventListener("click", () => {
if (pageIdx > 0) {
pageIdx -= 1;
changeText();
}
});

rightBTN.addEventListener("click", () => {
if (pageIdx < Arr.length - 1) {
pageIdx += 1;
changeText();
}
});

// 步骤 5:定义 changeText 函数
function changeText() {
pageIdxNUM.innerHTML = `${pageIdx + 1}/${Arr.length}`;
text.innerHTML = Arr[pageIdx];
}

// 步骤 6:初始化显示内容
changeText();
</script>
</body>
</html>