Javascript Dice roll返回未识别

时间:2012-03-06 18:20:16

标签: javascript dice

我正在为我的网站写一个骰子滚筒,感谢我的另一个问题,我可以在我的功能中输入数据,但我要求的数据返回未识别。

            //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"]));

我做错了什么?

1 个答案:

答案 0 :(得分:2)

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

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

修改:要跟进您的修改,您将获得NaN,因为dicekind未定义。 5 * undefined提供NaN,“非数字”。

您需要在this.dicekind内使用Dice才能使其正常运行。这是一种工作方式:

    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。