Javascript checking, if array element equals var?

59 views Asked by At

I have an array like this:

var str = "This is an example sentence with the number 1";
var array = str.split(' ');

// array[8] should be 1

Now i want to check, if a certain variable is the same as the value of array[8]. Therefor i thought I could use:

var checkingnumber = 1;

if(array[8] === checkingnumber) {
    console.log("success");
    return
}

This doesnt seem to work in my Code. So could anyone help me, how to fix that ?

1

There are 1 answers

3
Dominik On

The resulting array will be strings and === will compare the type as well. Use == or parseInt to make sure you compare apples with apples.

var checkingnumber = 1;

if(parseInt(array[8]) === checkingnumber) {
    console.log("success");
    return
}