0

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 ?

Frosty
  • 41
  • 1
  • 6
  • 4
    `1 !== "1"` ... `array[8] === "1"` does that help? – Jaromanda X Oct 03 '20 at 07:54
  • 4
    `===` also checks for types. the result of `str.split()` is an array of strings and not numbers (like `checkingnumber`), so your comparison fails – Sirko Oct 03 '20 at 07:55
  • One question - just to play devil's advocate here - is it **always** the 9th word in the sentence? Could it be the **last** word? Could it be somewhere else in the sentence? – ATD Oct 03 '20 at 08:29

1 Answers1

1

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
}
Dominik
  • 6,078
  • 8
  • 37
  • 61