【问题标题】:Javascript RandomNumberJavascript 随机数
【发布时间】: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


    【解决方案1】:

    1)随机数应该是

    Math.floor(Math.random() * openBoxes.length);
    

    添加一个将选择最后一个元素旁边的数字。即11

    2) splice数组从源数组中移除元素,你不必使用pop

    splice() 方法通过removingreplacing 现有元素和/或 adding 新元素 in place - MDN

    3)pop 不接受任何参数,总是从最后一个元素中删除一个元素。

    pop() 方法从数组中移除最后一个元素并返回 那个元素。 -MDN

    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);
    
      let moveIndex = openBoxes.splice(randomBox, 1); // remove specific index depending on the random number
      closedBoxes.push(moveIndex); // send the element to the closedBox array
    
      console.log(openBoxes);
      console.log(closedBoxes);
    }
    
    randomlySelect();
    randomlySelect();
    randomlySelect();

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 2010-11-10
      • 2011-07-10
      • 1970-01-01
      • 2016-04-01
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      相关资源
      最近更新 更多