【发布时间】:2021-06-16 03:11:06
【问题描述】:
我是 JS 的新手。我希望我能把这个问题问得足够清楚。我正在构建或编写一个接收随机输入并将随机输入替换为索引号相同位置的 js 程序。我创建了一个函数来生成随机数并替换 open box 数组的索引位置,然后将其移动到 closedboxes 数组。问题是,当我调用该函数时,它开始从 openBoxes 数组中删除 2 个元素,而不是每次调用该函数时删除一个。为什么会这样?
let openBoxes = ["box1", "box2", "box3", "box4", "box5", "box6", "box7", "box8", "box9", "box10", "box11"]
let closedBoxes = []
function randomlySelect() {
let randomBox = Math.floor(Math.random() * openBoxes.length + 1)
let moveIndex = openBoxes.splice(randomBox, 1) // remove specific index depending on the random number
closedBoxes.push(moveIndex) // send the element to the closedBox array
openBoxes.pop(moveIndex) // removes the element from the openBoxArray
console.log(openBoxes)
console.log(closedBoxes)
}
randomlySelect()
randomlySelect()
randomlySelect()
输出是:
(9) ["box1", "box2", "box3", "box4", "box6", "box7", "box8", "box9", "box10"] [Array(1)]
(7) ["box1", "box2", "box3", "box4", "box6", "box7", "box9"] [Array(1), Array(1)]
(5) ["box1", "box3", "box4", "box6", "box7"]
(3) [Array(1), Array(1), Array(1)]
感谢您的帮助。提前谢谢你!
【问题讨论】:
标签: javascript arraylist