Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
about javascript callback example

a = [3, 1, 2];

function b(v1, v2) {
  console.log('c', v1, v2);
  return 0
};

a.sort(b);

console.log(a);

a result of this script is like this

c 31 c 12 [3, 1, 2]

my question is

  1. Why is the function b being called twice?

  2. And in the first log console.log('c', v1, v2);

why the v1 value is the first array value of a. it's "3"

also why v2 is the second array value of "a"

in the second log console.log('c', v1, v2); Why are the 2nd and 3rd values of the array in v1, v2 the result is "c 1 2"

I can't understand

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The compare function is called repeatedly (being passed two elements from the array each time) until the array is completely sorted.

You have three items in the array so it has to be called at last twice.

The specific values that get passed each time will depend on the sort algorithm the JS engine has selected (this is an implementation detail, not something mandated by the JS specification). The order that elements are compared in a bubble sort will be different to a quick sort.

about 4 years ago · Juan Pablo Isaza Relatório

0

Why is the function b being called twice?

sort calls the callback as many times as it needs to in order to sort the array. Each time, it calls the callback with two elements from the array so the callback can tell it what order those two elements should be in.

And in the first log console.log('c', v1, v2);

why the v1 value is the first array value of a. it's "3"

also why v2 is the second array value of "a"

They won't be, necessarily; sort can call the callback with whatever elements it wants. The specific algorithm used for sorting isn't dictated by the specification. All that's dictated is that it be stable (not unnecessarily change the order of equivalent elements) and that it do its work using the provided callback, if any.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda