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

372
Visualizações
Why is includes() not working in javascript

const myArray = [
  [2, 4], "cat", "hamster", 9
]
console.log(myArray.includes("cat"))
console.log(myArray.includes([2, 4]))

output is true, false. does includes() not work for arrays inside of arrays? thanks

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

Because Array in js is a specific object, the [2,4] inside myArray is object and [2,4] that you switch to includes is anther object. If you want that includes return true you must do this:

var array = [2, 4]

const myArray = [array, "cat", "hamster", 9]

console.log(myArray.includes(array))
about 4 years ago · Santiago Gelvez Relatório

0

A string is a value type, so a comparison between two strings will compare the value of those strings. In your case the value cat. However, an array is an object with reference comparison, not value comparison. So when comparing two arrays the reference will be compared. That is if you compare the same object to itself the result will be true. However, as is the case in your example, if you compare two different objects even with all the properties set to the same value, the result will be false.

let a = [1,2];
let b = 2;
let c = "string";
let d = [1,2];

a === a; //true reference comparison comparing an object to itself
b === 2; //true value comparison
c === "string"; //true again value comparison, even though it's two different objects
a === d; //false the values are the same but it's reference  comparison

Array.includes iterates through the array and makes a comparison between the argument and the individual elements using the above comparison types depending on the types.

It's also important to note that includes uses strict comparison. That is if a comparison with === results in true then so would includes. It's not enough that == would result in true. "2" == 2is an example of a comparison that returns true where ["2"].includes(2) returns false

about 4 years ago · Santiago Gelvez 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