[英]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('')
將為您提供元素對象,而不是值,我想您的數組是由值組成的。
放一個.value
和var i = 0
; 功能范圍之外。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.