Javascript函数更改全局变量(数组)

时间:2014-12-25 19:18:55

标签: javascript arrays function

我正在尝试制作Yahtzee游戏。我有一个功能来检查骰子是否是一个小直线。

var sortedDice = rollDice().sort(); // rollDice() generates an array with 5 random numbers

我的功能是确定是否存在小直线:

function isSmStraight(checkSmStraight){
    var smStraight = false;

    var i = 1;
    var j = 0;

    //will remove a die if there are duplicates
    while(i < checkSmStraight.length){
        if (checkSmStraight[i] == checkSmStraight[j]){
            i++;
        } else {
            j++;
            checkSmStraight[j] = checkSmStraight[i];
            i++;
        }//end if else
    }//end while loop that moves duplicates to last index of array
    checkSmStraight.pop();//removes last index of array

    if (isLgStraight(checkSmStraight) == true){
        smStraight = true;
    } else if (checkSmStraight.length == 4 && checkSmStraight[checkSmStraight.length-1] - checkSmStraight[0] == 3){
        smStraight = true;
    }//end if else if
    return smStraight;
}//end function isSmStraight()

我已将sortedDice复制到另一个数组fourDice,我可以使用它来调用isSmStraight()。我希望这个函数只使用四索引数组,但它总是与sortedDice混淆,所以程序的其余部分使用四个骰子数组。 (这不是整个程序,只是我认为相关的部分。而且,程序已经完成,我只是想让评分函数首先正确)。

1 个答案:

答案 0 :(得分:2)

默认情况下,数组是在JavaScript中传递的。所以,如果你只是在做类似的事情      var fourDice = sortedDice 然后编辑fourDice,sortedDice也将被编辑 还请将您要复制sortedDice的代码放到问题中的fourDice。