How to return the last element of the array using the for?

1

I wanted to know how I get the last element of the array using the structure for in the case for decrement?

My code is this:

const a = n => n % 2 === 0;
function callbackfn (valorInserido, funcao) {
  for (valorInserido.length; i=0; i--) {
    if (funcao(valorInserido[i])) {
      return valorInserido[i];
    }
  }
}
console.log(callbackfn([3,5,2,4],(a)));

In case it was to return the number 4 , however it returns undefined .

    
asked by anonymous 25.01.2018 / 21:18

1 answer

2

The code has several errors.

The variable i is not initialized and has to initialize with the number of elements minus 1, since it starts from zero. The loop termination condition should be while i is greater than or equal to 0. If it asks if it equals 0, it will never be, unless the array has no elements, which does not it matters. And in fact if it were the same, it would be == , = is attribution.

I improved the style.

const condicao = n => n % 2 === 0;
function PegaUltimoCondicionamente(valorInserido, funcao) {
  for (var i = valorInserido.length - 1; i >= 0; i--) if (funcao(valorInserido[i])) return valorInserido[i];
}
console.log(PegaUltimoCondicionamente([3, 5, 2, 4], condicao));
    
25.01.2018 / 21:47