简体   繁体   English

函数返回相同的值

[英]function return the same value

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();

when I run the above code, it returnt the same array, evern I type different code into prompt alet box. 当我运行上面的代码时,它返回相同的数组,直到我在提示框内键入不同的代码。 I don't know why, can you please help me? 我不知道为什么,你能帮我吗? Thank you very much. 非常感谢你。

indexForm is a global variable. indexForm是一个全局变量。 When you call the guessStrToArr function for the first time array gets populated. 当您第一次调用guessStrToArr函数时,将填充数组。 The second time it gets repopulated. 第二次被填充。 When you're doing the comparison, your comparing the array against itself. 比较时,将数组与自身进行比较。 Try this: 尝试这个:

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

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

    return indexForm;
}

Also note that you are making no attempt to ensure that inStr.length is the same as N_CHOICES . 还要注意,您没有尝试确保inStr.lengthN_CHOICES相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么两个函数调用都返回相同的值? - Why both the function calls return the same value? valueOf函数设置为始终返回相同的值 - valueOf function set to always return the same value 从同一函数返回在函数内的事件处理程序中创建的值 - Return a value created in an event handler inside a function from the same function 在Mocha中如何从异步函数中的返回值先于在函数中的相同描述中使用相同的值? - How return value from async function in before in mocha and use same value in same describe in function? 为什么我的随机函数两次返回相同的值 - Why does my random function return the same value twice 如何在同一视图中将值从 javascript 函数返回到 django 模板? - How to return a value from javascript function to django template in the same view? 我可以为jQuery中的函数循环使用相同的返回值 - can I use same return value for function loops in jquery 如何同时从函数返回值和承诺? - How to return a value and a promise from a function at the same time? JQuery:ajax 请求返回值“未定义”在同一 function 内 - JQuery: ajax request return value “undefined” inside same function 当调用自身内部的函数时,第二次调用的返回值不相同 - when calling the function within itself return value is not the same in second call
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM