【问题标题】:Javascript function changing global variable (array)Javascript函数更改全局变量(数组)
【发布时间】:2014-12-26 03:31:36
【问题描述】:

我正在尝试制作 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 混淆,所以程序的其余部分使用四骰子数组。 (这不是整个程序,只是我认为相关的部分。另外,程序已经完成,我只是想先把评分功能弄好)。

【问题讨论】:

  • 如果你的函数,你必须在外部定义全局变量,比如var newvar = ""; function test() { newvar = "new text"; }
  • 您可能传递的是引用,而不是新数组,请使用 .slice() 创建副本。
  • 是的,全局变量是在函数外部定义的。使用 .slice() 效果很好。感谢两位的快速回复。

标签: javascript arrays function


【解决方案1】:

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

【讨论】:

  • 这正是我做错的。使用 .slice() 效果很好。现在我只需要弄清楚如何将其标记为已解决(该站点的新功能)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 2019-10-03
相关资源
最近更新 更多