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

149
Visualizações
JavaScript: Get value inside Number prototype function

I try to use includes in prototype but it does not work but I do not get the expected results:

Number.prototype.inList = function (list) {
  return list.includes(this);
}

let value = 0;

let find1 = value.inList([0,1]);
let find2 = [0,1].includes(value);

console.log("find1", find1); // false
console.log("find2", find2); // true

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

0

Using Number#valueOf:

The valueOf() method returns the wrapped primitive value of a Number object.

Number.prototype.inList = function (list) {
  return list.includes(this.valueOf());
}

let value = 0;
console.log(value.inList([0,1]));

about 4 years ago · Juan Pablo Isaza Relatório

0

This happens in non strict mode, where compatibility requires that this is always an object, not a primitive. So in your case this is an instance of the Number constructor, and of course that object does not occur in your list.

In strict mode your code works, as this will be the primitive value (number)

Number.prototype.inList = function (list) {
  "use strict";
  return list.includes(this);
}

let value = 0;

let find1 = value.inList([0,1]);
let find2 = [0,1].includes(value);

console.log("find1", find1); // true
console.log("find2", find2); // true

Here the strict mode is only effective on the function -- and this is enough for this issue. If your script has no "legacy dependencies", you should better set it globally.

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