I have a function in my JavaScript code which iterates over an array called background_check which has elements which are also arrays. I want to see if any element in this nested array is a 0 (each element is either a 0 or a 1). I do this with a for loop iterating over the array and calling the function recursively if any element is an array.
Here is my code:
function loop_checker(background_check) {
let loop_condition = false
let count = background_check.length
for (i=0;i<count;i++) {
if (typeof background_check[i] === 'object') {
let x = loop_checker(background_check[i])
if (x === true) {
loop_condition = true
}
}
else if (background_check[i] === 0) {
loop_condition = true
}
}
return loop_condition
The array in question is background_check = [1, 1, 1, 1, [1, 1, [1, 0]]]
The function iterates over the first four elements fine. It then gets to the i=4 case and iterates over the smaller array. When the new for loop gets to i=2 it iterates over the smallest list. Once it is all done it goes back down the call stack, but once it gets back to the first call of the function, i=4 has changed to i=3 and so it redoes the 5th element. This repeats infinitely; I cannot figure out why this has happened. I think it may be an issue with the scope of the i variable and recursion messing with that, but I am very new to JS.
P.S. sorry if this is poorly or incorrectly formatted, this is my first question. Thanks in advance!
ia local variable. You're overwriting it in the recursive call.loop_condition = trueyou should just return it, there's no need to keep looping.Array.some()function.