1

我正在为我的网站写一个掷骰子,感谢我的另一个问题,我可以在我的函数中输入数据,但我要求的数据返回身份不明。

            //Constant
        var consDie = new Array(3); //Implanté les élément de constance des dés. 
            for (var i = 0; i <= 2; i++){
                consDie[i] = 12 - (i * 2);
                console.log("D" + consDie[i]); 
            }

            var consNDice = 6; //Constante pour le nombre de dés
            var consAlign = {
                UnAl : consDie[2], 
                Bal : consDie[1], 
                Phys : consDie[0], 
                Ment : consDie[0]
            }; 
            //declaration of an object that contain the kind of dice that is rolled by powerup 

        //Variable integers
        var intDice = new Array(6); // contenant pour les résultats de dé.
        var intPhys = 0; //Phys Aligned answer counter
        var intBal = 0; //Neutral/balanced aligned answer counter
        var intMent = 0; //Mental aligned answer counter 


        //Dice Roll function

        function Dice (consAlign) {
            //Variables constant
            this.dicekind = consAlign;
            this.rollDice = function() {
                return Math.floor(Math.random()*dicekind);
            };

        }

        console.log(Dice(consAlign["Ment"]));

我做错什么了?

4

1 回答 1

2

Dice函数不返回值。看起来您打算用它来构造一个新对象:

console.log(new Dice(consAlign["Ment"]));

编辑:要跟进您的编辑,您会得到NaN因为dicekind未定义。5 * undefined给出NaN,“不是一个数字”。

您需要使用this.dicekindinsideDice才能使其工作。这是实现它的一种方法:

    function Dice(kind)
    {
        this._kind = kind;
    }

    Dice.prototype.roll = function()
    {
        return Math.floor(Math.random() * this._kind) + 1;
    };

    var dice = new Dice(6);

    console.log(dice.roll());

我还在 roll 方法中添加了 1,因此值的范围是 1..6,而不是 0..5。

于 2012-03-06T18:22:54.010 回答