0

我正在尝试编写一个简单的函数(checkCard)来检查另一个函数创建的随机卡是否已经在使用中。这是拨打电话的地点:

var uC;
// some code including creating the random card
checkCard(card, pCards, dCards, uC);
// uC becomes unidentified here

这是支票卡本身:

function checkCard(card, pCards, dCards, uC) {
    var tCards = pCards.concat(dCards), // an array containing all cards which are in use already
    i;
    for (i = 0; i < tCards.length; i = i + 1) {
        if (card.suit === tCards[i].suit && card.type === tCards[i].type) {
            uC = true; // card is in use already
            break;
        } else {
            uC = false; // card is not in use
        }
    }
    // it still works here: uC is either true or false
    return uC;
}

}

不知何故,它不起作用:checkCard 正确计算 uC,并且在“return uC”之前保持值“true”或“false”。但是在返回到原来的函数后,uC 变得“无法识别”。我究竟做错了什么?

提前致谢!

4

2 回答 2

1

该函数不会修改传递给函数的变量 uC,而是修改它的本地副本。您必须从返回中捕获 uC:

uC = checkCard(card, pCards, dCards);

由于您正在返回变量,因此您不需要将其作为参数传递,然后您将在函数中创建局部变量。

function checkCard(card, pCards, dCards) {
   var uC;
   ....}
于 2013-08-27T21:49:35.420 回答
0

在原始代码中,您需要

uC = checkCard(card, pCards, dCards, uC);

要么,要么不传入uC函数调用——如果你把它关闭,它将继续是一个全局变量,而你uC在函数中完成它的方式是一个局部变量。

于 2013-08-27T21:47:57.927 回答