Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda