【发布时间】: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