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

303
Vistas
JS indexOf() not giving result of inputted number

I am trying to see the indexOf() of an array of numbers for an inputted value.

For regular numbers in the array it is not working, but if the number in the array uses quotes (such as "3"), it somehow works.

Why is this not working for a regular number without quotes?

<p><input type="number" id="inNum"></p>
<button onclick="indexCheck()">Check</button>
<p id="result"></p>

<script>
var arr = [1, 2, "3", 4];

function indexCheck() {
    var x = document.getElementById("inNum").value;
    
    var ind = arr.indexOf(x);

    document.getElementById("result").innerHTML = ind;
    };
</script>

In the above example, 1, 2, and 4 give a result of -1 (so they are not found in the array) but 3 give result of 2 (so it is found in the array at position 2).

Yet somehow a non-inputted number can be found and it works fine:

<button onclick="indexCheck()">Check</button>
<p id="result"></p>

<script>
var arr = [1, 2, "3", 4];

function indexCheck() {
    var x = 2;
    
    var ind = arr.indexOf(x);

    document.getElementById("result").innerHTML = ind;
    };
</script>

What am I doing wrong? Any help would be appreciated!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Your input "number" is actually a string. Here's documentation of the HTMLInputElement interface; note that the value property is of type string.

So that's why it can find the value "3" in your array, but not the number 3. In order to convert it to a number, you can use the Number global function:

var string = "3";
var number = Number(string); // will be 3
about 4 years ago · Juan Pablo Isaza Denunciar

0

<script>
    var arr = ['1', '2', '3', '4'];
    function indexCheck() {
        var x = document.getElementById("inNum").value;
        var ind = arr.indexOf(x);

        document.getElementById("result").innerHTML = ind
    }
</script>
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