Home > Back-end >  JS indexOf() not giving result of inputted number
JS indexOf() not giving result of inputted number

Time:06-16

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!

CodePudding user response:

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

CodePudding user response:

<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>
  • Related