0
N_ALPHA = 6;
N_CHOICES = 4;
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var alphabet = ALPHABET.substring(0, N_ALPHA);
var indexForm=new Array();
function guessStrToArr(inStr)
{ 
  {
    for (i=0;i<N_CHOICES;i++)
    {
       indexForm[i]=alphabet.indexOf(inStr.charAt(i).toUpperCase());
    }
  }
 return indexForm;
}

function numBulls(guess, goal)
{
  guess=new Array (guessStrToArr(prompt('enter your guess1')));
  alert(guess);
  goal=new Array(guessStrToArr(prompt('enter your guess2')));
  var checkArray = new Array (guess.concat(goal); 
  alert(checkArray);

  var count=0;

  for (i=0;i<N_CHOICES;i++)
  {
    if (guess[i]===goal[i])
    {
      count++
    }
  }
  return count;
}

numBulls();

当我运行上面的代码时,它返回相同的数组,每次我在提示框输入不同的代码。我不知道为什么,你能帮帮我吗?非常感谢。

4

1 回答 1

1

indexForm是一个全局变量。当您guessStrToArr第一次调用该函数时,数组会被填充。第二次重新填充。当您进行比较时,您将数组与自身进行比较。尝试这个:

function guessStrToArr(inStr) { 
    var indexForm = new Array();

    for (i = 0; i < N_CHOICES; i++) {
       indexForm[i] = alphabet.indexOf(inStr.charAt(i).toUpperCase());
    }

    return indexForm;
}

另请注意,您没有尝试确保它inStr.lengthN_CHOICES.

于 2013-01-26T13:36:07.500 回答