函数内的console.log和函数后的console.log结果不同,为什么以及如何解决? (递归函数,掷骰子)

问题描述 投票:0回答:0

我构建这个函数是为了打印出一卷多个骰子的所有可能结果。然而,当我控制台记录函数内的每个变体时,结果如预期:所有变体都在那里。但当通过部署 .push() 用每个变体填充函数内的数组时,情况并非如此。数组会填充最后一个变化,并且填充的次数与可能的变化次数一样多。

示例:在函数内记录:[1,1]、[1,2]、[1,3]、... 示例:在函数外部记录:[6,6], [6,6], [6,6], ...

我不明白为什么,想知道如何解决。

function roll(numberOfDice = 2, dice = 6) {

    //create an array to get all the numbers
    let numbers = Array.from(Array(dice), (v, k) => k + 1);
    //create an array of the dices and set all to 1
    let digits = Array.from(Array(numberOfDice), v => 1);
    // to do: how many dices to add

    // starting point of all possible outcomes
    let count = 0;
    // maximum of possible outcomes
    let maxVariations = Math.pow(dice, digits.length);
    // and array for all possible outcomes, which we like to fill with the following funt
    let variations = [];

    //map foreach digit map all numbers, where for each number all numbers are mapped and so on...
    digits.forEach((v, i, d) => {

        function deepDown(d, i) {

            numbers.map((num) => {

                d[i] = num;

                if (i == d.length - 1) {
                    variations.push(d);
                    console.log(variations[variations.length - 1]);
                }

                if (d[i + 1] != undefined) {
                    deepDown(d, i + 1);
                }
            });
        }
        deepDown(d, i);

    });

    console.log(variations);
}

roll();

javascript recursion dice
© www.soinside.com 2019 - 2024. All rights reserved.