How to traverse an element by one in an array JS

0

Personally, good afternoon. I'm doing a function that has the same utility as ANY .

What is the idea, is to know if it has any number smaller than the given in the function inside the array, regardless if it is in the first or last position of the array. If exister returns TRUE , otherwise, returns FALSE

The code looks like this:

const numerosFora = [1];

function qualquer (num1, func){
	for(let i = 0; i < num1.length; i++){
  	for(let i = 0; i < func.length; i++){
    	if(num1[i] < func[i]){
      		return true
      } else {
       		return false
      }
      	
      }
    }
  	
}

  

console.log(qualquer([1,0],numerosFora))

But it only returns if the number is in the first position, in case 0.

    
asked by anonymous 06.02.2018 / 19:50

1 answer

0

Your for has problem because both use the same variable i , so in the num1[i] < func[i] comparison, i will always be the last for .

Another thing, when you put a return , the loop ends, that is, the remaining items of the array that should eventually be traversed, will no longer be.

As you just want to check if true returns and stops the loop when it does, just leave the return true in the loop (and change the second for variable):

const numerosFora = [1];

function qualquer (num1, func){
  for(let i = 0; i < num1.length; i++){
    for(let x = 0; x < func.length; x++){
      if(num1[i] < func[x]){
        return true;
      }else{
        console.log(false); // apenas como exemplo para mostrar no console
      }
    }
  }
}

console.log(qualquer([1,0],numerosFora))
    
06.02.2018 / 20:57