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

119
Visualizações
JavaScript. 10%5 === 0 --> false?

Please help to find mistakes in my code:

function multipleOfIndex(array) {
    return array.forEach( item => console.log(item%array.indexOf(item) === 0) )
}
    
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false 

obviously, I was expecting

console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, true 

Thanks!

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

0

The problem is relying on indexOf when more than one value is the same in the array - array.indexOf(10) is always 4, see the extended log here:

function multipleOfIndex(array) {
    return array.forEach( item => console.log(item,array.indexOf(item),item%array.indexOf(item) === 0) )
}
    
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false

The solution is to use the forEach index parameter (2nd one) https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

function multipleOfIndex(array) {
    return array.forEach( (item,idx) => console.log(item%idx === 0) )
}
    
console.log(multipleOfIndex([68, -1, 1, -7, 10, 10])) // false, true, false, false, false, false

about 4 years ago · Juan Pablo Isaza Relatório

0

The [indexOf] method returns the first index of a given element that can be found in the array. If it does not exist, it returns - 1. So the [indexOf] value of the last 10 is 4.

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