递归函数无法使用Javascript

递归函数无法使用Javascript,javascript,Javascript,我想检查数组元素中的第一个索引是否等于输入,如果等于,我想让它递增并检查下一个索引,依此类推。但我的代码只对第一个索引进行递增,然后再次返回第一个索引。为什么 var i=0 function compareInput(array){ if(result[i]==document.getElementById('input')){ i++; compareInput(array); } else{ c

我想检查数组元素中的第一个索引是否等于输入,如果等于,我想让它递增并检查下一个索引,依此类推。但我的代码只对第一个索引进行递增,然后再次返回第一个索引。为什么

    var i=0

    function compareInput(array){


    if(result[i]==document.getElementById('input')){
         i++;
         compareInput(array);
    }
    else{
       console.log('not equal');
   }
 }

每次调用compareInput时,您将
var i=0
,因此if将始终是
if(结果[0]==document.getElementById('input'))
。 另外,
document.getElementById(“”)
将为您获取元素对象,而不是值,我假设您的数组是由值组成的


输入
.value
var i=0
;超出函数范围。

这是我比较输入和递归函数的方法。
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<input id="input"></input>

<script type="text/javascript">

    function compareInput(array){
      var i=0;

      return function(array){
            if(array[i]== document.getElementById('input')){
                 i++;
                 compareInput(array);
                 console.log("equal %d",1);
            }
            else{
               console.log('not equal');
           }
      }
 }

var compare = compareInput();
compare([document.getElementById('input')]);
</script>
</body>
</html>
我使用函数作为返回,因为I variable作用域(其中I variable仅在compareInput函数中可用)可以在函数内部(即compareInput函数内部)访问

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<input id="input"></input>

<script type="text/javascript">

    function compareInput(array){
      var i=0;

      return function(array){
            if(array[i]== document.getElementById('input')){
                 i++;
                 compareInput(array);
                 console.log("equal %d",1);
            }
            else{
               console.log('not equal');
           }
      }
 }

var compare = compareInput();
compare([document.getElementById('input')]);
</script>
</body>
</html>

函数比较输入(数组){
var i=0;
返回函数(数组){
if(数组[i]==document.getElementById('input')){
i++;
比较输入(数组);
控制台日志(“等于%d”,1);
}
否则{
console.log('notequal');
}
}
}
var compare=compareInput();
比较([document.getElementById('input'));

在数组中查找字符串的一些不同方法

函数isInArray(i,a){
返回!!~a.indexOf(i);
}
函数isInArrayWithLoop(i,a){
var c;
对于(c=0;c);
文件。写入(isInArray('yellow',['red','yellow','green','blue'])+“
”; //循环法 写(isInArrayWithLoop('black'、['red'、'yellow'、'green'、'blue'])+“
”; 写入(isInArrayWithLoop('yellow'、['red'、'yellow'、'green'、'blue'])+'
); //递归方法 编写(isInArrayWithRecursion('黑色',['红色','黄色','绿色','蓝色')+'
); write(isInArrayWithRecursion('yellow'、['red'、['yellow'、'green'、'blue'])+'
); //一些方法 文件。写(带一些('黑色',['红色','黄色','绿色','蓝色')+'
);
文档。写入(带有一些('yellow',['red','yellow','green','blue'])+“
是否有理由递归执行此操作,而不是使用
for
循环?@pun-每次执行
比较输入时
i=0
。如果您不想重置它,请将
i=0
设置在
compareInput
函数的范围之外。@pun:对,您不重置它。但是,每次调用
compareInput
,它都会创建一个新的
i
变量,该变量被初始化为
0
。除非您是为了学习递归而做一些功课,否则只需使用for循环。
result
在哪里定义?