繁体   English   中英

递归函数不起作用Javascript

[英]recursive function not working Javascript

我想检查数组元素中的第一个索引是否等于输入,如果是,我希望它增加并检查下一个索引等等。但是我的代码只对第一个索引执行它,增加然后再次返回到第一个索引。为什么?

    var i=0

    function compareInput(array){


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

这是我将输入与递归函数进行比较的方法。 我使用函数作为返回,因为i 变量范围,其中i 变量仅在 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>

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

 function isInArray(i, a){ return !!~a.indexOf(i); } function isInArrayWithLoop(i, a) { var c; for (c = 0; c < a.length; c++) { if (i === a[c]) { return true; } } return false; } function isInArrayWithRecursion(i, a, c) { // initialize c with o if not given c = c || 0; // return false if not c < a.length // if c < a.length // then return the result of the vomparison with the specified element and i // if false, return the result of a new call of recusion with an increased counter return c < a.length && (i === a[c] || isInArrayWithRecursion(i, a, c + 1)); } function isInArrayWithSome(i, a) { return a.some(function(aa) { return i === aa; }); } // direct approach document.write(isInArray('black', ['red', 'yellow', 'green', 'blue'])+'<br>'); document.write(isInArray('yellow', ['red', 'yellow', 'green', 'blue'])+'<br>'); // loop approach document.write(isInArrayWithLoop('black', ['red', 'yellow', 'green', 'blue']) + '<br>'); document.write(isInArrayWithLoop('yellow', ['red', 'yellow', 'green', 'blue']) + '<br>'); // recursion approach document.write(isInArrayWithRecursion('black', ['red', 'yellow', 'green', 'blue']) + '<br>'); document.write(isInArrayWithRecursion('yellow', ['red', 'yellow', 'green', 'blue']) + '<br>'); // some approach document.write(isInArrayWithSome('black', ['red', 'yellow', 'green', 'blue']) + '<br>'); document.write(isInArrayWithSome('yellow', ['red', 'yellow', 'green', 'blue']) + '<br>');

每次调用 compareInput 时,设置var i = 0; ,因此 if 总是if (result[0] == document.getElementById('input')) 此外, document.getElementById('')将为您提供元素对象,而不是值,我想您的数组是由值组成的。

放一个.valuevar i = 0 ; 功能范围之外。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM